Reputation: 63905
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?
Upvotes: 0
Views: 357
Reputation: 9759
"Why not just make it a regular DateTime and return null"
DateTime can't be null.
Upvotes: 0
Reputation: 1
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.
Upvotes: 0
Reputation: 70228
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.
Upvotes: 0
Reputation: 5965
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'
Upvotes: 1
Reputation: 122212
Because DateTime is a .NET value type. Just like int and char it cannot be null
Upvotes: 10
Reputation: 23613
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.)
Upvotes: 0