Jefferson
Jefferson

Reputation: 43

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();

Upvotes: 0

Views: 6687

Answers (2)

GMD
GMD

Reputation: 40

Try using

 if  ((new DateTime()).Equals(dt)) {
...
}

Upvotes: 1

tsvedas
tsvedas

Reputation: 1069

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.

Upvotes: 3

Related Questions