C# Null Coalesce Operator
The ?: conditional operator is commonly used by C# programmers and most developers understand how it works.
This operator is of the form:
condition ? first_expression : second_expression
where if the condition is true, the first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. This is commonly used as an elegant replacement for if-else blocks.
But… have you run into the ?? operator?
This operator is called the null-coalescing operator and can also be used to simplify a special if-else case.
Imagine that you had the following code that was used to display a user’s location… but it might not be set:
...
String locationDisplayString= user.Location;
if(locationDisplayString.Location==null)
{
locationDisplayString =”not specified”;
}
...This seems reasonable. If the user has provided a location, then we display it, otherwise we display “not specified” to explain that the user did not want to provide a location.
Could we make this code a bit cleaner ?
The ?? operator can be used to evaluate an assignment expression where there is a possibility of the assignment resulting in a null value. It could be described like this:
left_operand ?? right operand
If the left_operand is not null, it will be returned as the result. Otherwise, the right operand will be returned. So.. we could simplify our above code as follows:
...
string locationDisplayString= user.Location ?? “not specified”;
...
Fancy. This operand comes in handy when assigning nullable types to non-nullable types. Generally if you try to assign a nullable type to a non-nullable type you would get a compile-time error.
int? nullableInt=null;
int nonNullableInt=nullableInt;//error. bad.
But, you could take advantage of the ?? operator and set a default value in the event that the nullable int is in fact, null.
int? nullableInt=null;
int nonNullableInt=nullableInt ?? -1;//no error. all good.
You might be thinking… when would I use this?
This could be used in the new ASP.NET MVC Framework controller actions. If your routing is using the default route like "{controller}/{action}/{id}" and you wanted to use an int parameter to represent the id in your action method... what would happen if no id parameter was supplied in the request ?
You could use a nullable int type - and of course you could use the ?? operator to supply a default value and gracefully handle this case.