Thursday, March 17, 2011

Null Coalescing operator - C#

v  One of the useful language features of C# is the ?? "null coalescing" operator.  This provides a nice, short way to check whether a value is null, and if so return an alternate value.

v  The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

v  ?? operator in Action

//If userId is not null then it will return userId value 
//If userId is null then it will return -1

int? userId = null;
int customerId = userId ?? -1; 
//[Output]: customerId = -1;            

int? userId = 12;
int customerId = userId ?? -1; 
//[Output]: customerId = 12;

//The ?? operator also works with reference types:

string param = "Hello, This is C#";
string message = param ?? "No message"; 
//[Output]: message = "Hello, This is C#"


Hope this helps. Happy Coding !

0 comments: