C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Main: Inside the Main method, a new instance of the Test class is allocated with the parameterless constructor.
Test: The Test constructor accesses the _importantTime DateTime member variable. It compares the value against DateTime.MinValue, which returns true.
Info: The line "DateTime dateTime1 = null" is commented out. This is because it won't compile, and the C# compiler will give you an error.
Note: If this doesn't make sense to you, think of it in the same way as assigning an int to null.
C# program that shows null DateTime and MinValue
using System;
class Test
{
DateTime _importantTime;
public Test()
{
//
// Test instance of DateTime in class.
//
Console.WriteLine("--- Instance DateTime ---");
Console.WriteLine(_importantTime);
Console.WriteLine(_importantTime == DateTime.MinValue);
}
}
class Program
{
static void Main()
{
//
// Execute code in class constructor.
//
Test test = new Test();
//
// This won't compile!
//
// DateTime dateTime1 = null;
//
// This is the best way to null out the DateTime.
//
DateTime dateTime2 = DateTime.MinValue;
//
// Finished
//
Console.WriteLine("Done");
}
}
Output
--- Instance DateTime ---
1/1/0001 12:00:00 AM
True
Done
Info: We looked at the exact value of DateTime.MinValue, which is "1/1/0001 12:00:00 AM" (a long time ago).
And: The DateTime type never points at anything. It stores all its data in place of that reference, directly in the variable itself.
Error 1: Cannot convert null to System.DateTime because it is a non-nullable value type.