Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable types in .NET missing methods

Tags:

.net

nullable

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?

like image 257
Abe Miessler Avatar asked Aug 02 '26 20:08

Abe Miessler


2 Answers

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

like image 200
Igor Zevaka Avatar answered Aug 04 '26 15:08

Igor Zevaka


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());
    ...
}
like image 28
Thomas Levesque Avatar answered Aug 04 '26 17:08

Thomas Levesque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!