mardi 26 janvier 2016

C# Determine difference between DateTime and DateTime? (Nullable)

I am trying to determine the difference between a DateTime and a DateTime? using reflection. Please see my test code below:

    public class TestClass
    {
        public DateTime testDate1 { get; set; }
        public DateTime? testDate2 { get; set; }
    }

    public void Test()
    {
        TestClass testing = new TestClass();
        var props = typeof(TestClass).GetProperties();
        foreach (PropertyInfo p in props)
        {
            object o = p.GetValue(testing);
            if (typeof(DateTime?).IsInstanceOfType(o))
            {
                o = DateTime.Now;
            }
            if (typeof(DateTime).IsInstanceOfType(o))
            {
                if (((DateTime)o) == DateTime.MinValue)
                {
                    o = null;
                }
            }
            Console.WriteLine(string.Format("{0} = {1}", p.Name, (o ?? "NULL").ToString()));
        }

    }

The output of this code is the opposite to what i would expect. Currently the output is:

testDate1 = 26/01/2016 16:15:00

testDate2 = NULL

I am expecting testDate1 to be null and testDate2 to contain the value.

When debugging this code, it seems that the first pass using testDate1 passes both of the typeof if statements, the second fails both of the if statements. Can anybody help me understand and hopefully try and catch the specific nullable instance of the date time?

To note i have also tried switching to a definition and test on Nullable just in case, but it made no difference.

Many thanks!





Aucun commentaire:

Enregistrer un commentaire