Home
Map
DateTime.MinValue (Null DateTime)Use the DateTime.MinValue field to initialize DateTime instances. It is a special value.
C#
This page was last reviewed on Mar 2, 2022.
DateTime.MinValue. In C# programs, DateTime cannot be assigned to null. It has a default value that is equal to DateTime.MinValue.
Value type. The DateTime type is a value type—just like an integer. Instead of null assignment, we can use the DateTime.MinValue field.
Nullable
DateTime
This example checks the initial value of a DateTime member variable. When you have a DateTime instance at the class level, it is initialized to DateTime.MinValue by default.
class
null
Detail Inside the Main method, a new instance of the Test class is allocated with the parameterless constructor.
Detail The Test constructor accesses the 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, think of it in the same way as assigning an int to null.
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"); } }
--- Instance DateTime --- 1/1/0001 12:00:00 AM True Done
Null. When you try to assign a DateTime to null, the compiler will give an error "Cannot convert null to System.DateTime". The null value in the language is only used on reference types.
And The DateTime type never points at anything. It stores all its data in place of that reference, directly in the variable itself.
Cannot convert null to System.DateTime because it is a non-nullable value type.
Readonly. We can use the readonly field DateTime.MinValue. In the base class library, the MinValue field is a public static readonly field. It won't change throughout a program's execution.
readonly
A summary. We looked at some issues relating to null DateTime variables in C# programs. We can use the DateTime.MinValue field to initialize new DateTimes.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 2, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.