?? and ?:

This is more of an aide-mémoire for me, than info for anybody else, because I can never remember which is which or what order the expressions use.

??  Operator – the null-coalescing operator

– this is lifted straight from here.

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns:

the left-hand operand if the operand is not null; otherwise it returns the right operand.

A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

For more information, see Nullable Types (C# Programming Guide).

The result of a ?? operator is not considered to be a constant even if both its arguments are constants.

Ken Beckett pointed out that this operator is right-associative (which is different from the majority of C# binary operators).

?:  Operator – the conditional operator

– this is lifted straight from here.

condition ? first_expression : second_expression;

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

Seant77 notes:

If you are using this operator with a nullable type and want to be able to use null explicitly, you have to cast it as the nullable type.

Lets say myClass has an integer member id:

int? id = (myClass == null) ? null : myClass.MemberID;

This will give an error. “Type of conditional expression cannot be determined because there is no implicit conversion between ‘<null>’ and ‘int'”

This will work:
int? id = (myClass == null) ? (int?)null : myClass.MemberID;

I can never remember the order of the latter operator and most search engines reject ?: so it’s always a pain to find.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: