Using NULL-COALESCE Operator in C#

Jun 8 2010 7:32 AM
Hi,

I am sharing a tips on "Using NULL-COALESCE Operator in C#".

To my knowledge perhaps the least used operator in C# is the null-coalescing operator .
But you can use it effectively to reduce the lines of code you write .
 
The null-coalesce operator can be used to define / return a default value for a nullable value type / reference type and this is represented by two consecutive question marks (??).
 
Here is how you can use it :
 
 
Ex. 1 : Assign default value to Value type
 
 // define a nullable int
 int? x = null;
 
 // assign a value to another integer, but check if it contains null value
 // if a null is there, assign a default value
 int y = x ?? -1;

Hope you find this tips useful and of assistance.

Thanks,
Bijayani

Answers (1)