tags:

views:

41

answers:

2

I noticed today that if you declare a nullable DateTime object you don't get the same set of functions as you do when you have a standard DateTime object.

For example:

DateTime? nullableDT = DateTime.Now;
DateTime regularDT = DateTime.Now;

in the code above nullableDT cannot use any of the following functions:

ToFileTime
ToFileTimeUtc
ToLocalTime
ToLongDateString
ToLongTimeString
ToOADate
ToShortDateString
ToShortTimeString
ToString(IFormatProvider)
ToString(String)
ToString(String, IFormatProvider)
ToUniversalTime

This is the short list, there are many more methods not available.

Why is .NET behaving like this? I worked around it by throwing a Convert.ToDateTime() around my nullable date but that seems krufty... Is there a better way?

+5  A: 

That's because you need to call Nullable<T>.Value to get the actual DateTime value.

Igor Zevaka
You might also consider using `Nullable<T>.GetValueOrDefault()` which doesn't throw an InvalidOperationException if `HasValue` is false.
codekaizen
+1  A: 

A Nullable<T> isn't a T, it just wraps a T. So it doesn't have the members defined on T. If you want to access the methods of T, you can do that:

if (nullableDT.HasValue)
{
    Console.WriteLine(nullableDT.Value.ToShortTimeString());
    ...
}
Thomas Levesque