Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Basic question: What is '?'? [duplicate]

Tags:

c#

.net

nullable

I'm wondering what ? means in C# ?
I'm seeing things like: DateTime? or int?. I suppose this is specific to C# 4.0?
I can't look for it in Google because I don't know the name of this thing.
The problem is I'm using DateTime and I have a lot of cast errors (from DateTime to DateTime?).

Thank you

like image 852
Amokrane Chentir Avatar asked Apr 23 '10 14:04

Amokrane Chentir


1 Answers

It's a shorthand for writing Nullable<int> or Nullable<DateTime>. Nullables are used with value types that cannot be null (they always have a value).

It is not specific to C#4 by the way.

You can only assign an int? to an int if it has a value, so your code would have to do things like:

int? n = 1;
int i = n ?? default(int); //or whatever makes sense

Also note that a Nullable has two properties, HasValue and Value that you can use test if a value has been set and to get the actual value.

like image 124
Klaus Byskov Pedersen Avatar answered Sep 21 '22 18:09

Klaus Byskov Pedersen