Alex Rivera | Logout

C# - Basic question: What is '?'?

Asked 2010-04-23T14:34:16.433
16

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

Edit
Report

1 Answer

5

The ? is a nullable value type.

You can use the ?? operator to mix it with value types:

const int DefaultValue = -1;

// get a result that may be an integer, or may be null
int? myval = GetOptionalIdFromDB();

// the value after ?? is used if myval is null
int nonNullable = myval ?? DefaultValue;

The nullable type can be compared to null, so the above is shorthand for:

if( myval != null ) {
    nonNullable = myval.Value;
} else {
    nonNullable = DefaultValue;
}

But I prefer ??

answered 2010-04-23T14:43:02.707

Your Answer