Null-coalescing operator in C#
Posted by Manoj Garg on May 12, 2009
While surfing around I can across a term called “null-coalescing operator”. After searching about it, I came to know that C# has an operator ?? . well I didn’t new about it before so thought of writing about it.
The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.
int? x = null;string str = "Hello World !!";int y = x ?? -99; // Here Y will be -99 since X is nullstring newStr = str ?? "Default Hello World !!"; // here newStr will be "Hello World !!"
PS: This operator reminded me of similar functions available in SQL Server like ISNULL, COALESCE