I am pretty sure that most of the guys has never knew this operator and its also very rarely used. Since C# provides this and this is very useful and handy at certain times.
The short from of null-coalescing operator is ??.
It actually takes two operands. So it returns the left hand operand if it is not null else returns right operand. So this is very useful while initializing any variable. let’s see a example
string name = null; string otherName = "Brij"; string userName = name ?? otherName; Console.WriteLine(userName);
As you can see, here is name is null then userName is assigned to otherName. and it will print Brij.
This is also useful in scenario like if the data/message/string is null then if you want to show some default message. Say I have array of bookNames and I have to find to 4th index name but say 4th index doesn’t exist at all then we’ll show a custom message like index does not exist like
static void Main(string[] args) { string bookName = GetBookName(4) ?? "No book found at this index"; Console.WriteLine(bookName); Console.ReadKey(); } private static string GetBookName(int index) { String[] arrayOfBooks = new string[3] { "WorkFlow Foundation", "CLR via C#", "ASP.NET Professional" }; if (arrayOfBooks.Length > index) return arrayOfBooks[index]; else return null; }
Above example is self explanatory and it show the output No book found at this index. As no book is available at 4th index and GetBookName returns null.
One very good thing, It is not only works with Reference types but also works with Nullable types( I discussed Nullable types in earlier post) as well. It cannot work with Value types because value type cannot have null.
Also this operator works very efficiently with expressions as well. Like
static void Main(string[] args) { Func<string> fun = () => GetName() ?? "No Name"; Console.WriteLine(fun()); Console.ReadKey(); } private static string GetName() { return null; }
Hope this will help you guys.
Cheers,
Brij
