is the DateTime empty?

Have you ever tryied to check a DateTime for the state "not set"?

Some of you would say "this is easy, I will check the variable for null" like this:

1
2
3
4
if (myDateTime == null)
{
      // it is empty
}

The funny fact is: this will never work. But why?

Well, the answer is that a DateTime Object is not nullable. That means it will never be null even if you just created it.

So how should you check it if it won't be null?
There are two ways to do it.

Way 1:
Check for the value a DateTime has after creating it:

1
2
3
4
5
6
DateTime datetime = new DateTime();

if (datetime == DateTime.MinValue)
{
    // it is empty
}

Now some of you are thinking maybe my variable is set with the MinValue. And so we are coming to way 2:
Make the DateTime nullable.

1
2
3
4
5
6
DateTime? datetime = null;

 if (!datetime.HasValue)
 {
     // it is empty
 }

Comments

Popular posts from this blog

How to support multiple languages in WPF