tags:

views:

122

answers:

6

I'm currently working with a library and noticed something weird when using functions I already made(where I must do casting).

The library had a function defined like

public DateTime? GetDate(){..}

What is the point of this? Why not just make it a regular DateTime and return null as normal if there is some error getting the date? Am I missing something significant about Nullable types?

A: 

Value types cannot be Null. A Nullable (often writen DateTime?) can have a value of null. This is also true for all value types. If you want a variable to hold a valid Integer or Null, you need to declare a value type of Int32?

You cannot have a Nullable string. I mention this because although strings are reference types they behave like value types in many ways; I have been people try to declare Nullable. (Okay, I admit it. It was me.)

Patrick Karcher
+9  A: 

Because DateTime is a .NET value type. Just like int and char it cannot be null

George Mauer
A: 

DateTime is a value type. It cannot have a value of null assigned to it.

Edit: If you attempt to use the ? operator on a reference type, you get the following error:

The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

Nick
A: 

DateTime is a structure and thus a valid nullable because it's a value type. But you're right, one can't make reference types nullable because they can be assigned null already.

AndiDog
A: 

Not all types are reference types. For instance you cannot do something like

int x = null;

because int is value type. DateTime is value type.

Tom
A: 

"Why not just make it a regular DateTime and return null"

DateTime can't be null.

kekekela