Tag Archives: operator

C# – ?? – Null Coalescing Operator

Very often you have to check different object if they are not null and then perform a kind of action with them. You would do this check like this:

MyClass value = this.getValueBySomeMethod();
Console.WriteLine((value == null) ? "No value returned" : value);

In C# 2.0 there is very useful operator – ?? (knows as null coalescing operator). It checks if the left operand is equal to null returns the right one. If it is not null => it returns it. Here is a simple example.

MyClass value = this.getValueBySomeMethod();
Console.WriteLine(value ?? "No value returned");

Isn’t is awesome? :) You safe writing redundant code and your code looks more pleasant.

Filled under C#. No Comments.