Search code examples
c#datetimedefault-value

Datetime - GetValueOrDefault


Can I check if this is the default value without using a hard coding values 1/1/0001 12:00:00 AM? If it is the default set it to null?

DateTime? dt= null;
DateTime? datetimeVM;

datetimeVM = dt.GetValueOrDefault();

Solution

  • C# has built-in keyword for getting default value of a type: default(T) where T is your wanted type.

    So if you want to check if your Nullable<DateTime> (thats why there's ? by DateTime) has default DateTime value, just use

    if (datetimeVM == default(DateTime))
    {
        // datetimeVM has default DateTime value
    }
    

    However, Nullable<T> is a wrapper class for structures that allows them have null value, therefore default value of Nullable<T> is null.