Friday, July 19, 2013

The unassigned state for a DateTime type in C# is not equivalent to null as I had hoped.

The first two asserts in this test will fail:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Whatever.Test
{
   [TestClass]
   public class UnitTest
   {
      private DateTime foo;
      
      [TestMethod]
      public void TestMethod()
      {
         Assert.AreEqual(foo, null);
         DateTime? bar = foo;
         Assert.AreEqual(bar, null);
         foo = new DateTime(1974,8,24);
         bar = foo;
         Assert.AreNotEqual(bar, null);
         Assert.AreEqual(bar, new DateTime(1974, 8, 24));
      }
   }
}

 
 

This test passes:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Whatever.Test
{
   [TestClass]
   public class UnitTest
   {
      private DateTime foo;
      
      [TestMethod]
      public void TestMethod()
      {
         Assert.AreEqual(foo, new DateTime(0001, 1, 1));
         DateTime? bar = foo;
         Assert.AreEqual(bar, new DateTime(0001, 1, 1));
         foo = new DateTime(1974,8,24);
         bar = foo;
         Assert.AreNotEqual(bar, null);
         Assert.AreEqual(bar, new DateTime(1974, 8, 24));
      }
   }
}

No comments:

Post a Comment