?? 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.


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;



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.