Back to Basics – Null-Coalescing Operator
Yesterday during an EF4 course that I’m giving at a customer I showed an example for a property that is set using the null-coalescing operator. Since some of the students asked me what is this operator, I gave a small explanation and thought that it’s something that I can share here in the blog. So here it goes…
The null-coalescing operator or ?? can be very useful when you want to check nullity of a reference type or nullable types. When it is used, it returns the left-hand side of the operator if it is not null. If the left-hand side is null, it returns the right side. Here is an example of how you can use the operator in a property to get a lazy initialization of the property:
This property is taken from an Entity Framework generated ObjectContext. When the getter is used, first there is a check whether _contactDetails is null and if not the getter will return its value. If the _contactDetails is null then the right side of the operator will be evaluated and the CreateObjectSet method will run and create the ContactDetails object set. The result of the evaluation will be returned by the operator.
There are other scenarios to use the null-coalescing operator such as checking whether a nullable type is null in order to set its value if exists in a simple type and if not to set a default value. For example:
The example shows the use of the operator in order to determine whether x is null. in the example y will be equal to x, unless x is null. If x will be null y will be set to -1.
Lets sum up, the null-coalescing operator is a very simple operator that can be very helpful in null checking scenarios.