Yesterday during an EF4 course that I’m teaching to 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 this operator is, I gave a small explanation and thought that it’s something that I can share here in the blog. So here it goes…
Null-Coalescing Operator
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:
public ObjectSet<ContactDetails> ContactDetails
{
get { return _contactDetails ?? (_contactDetails = CreateObjectSet<ContactDetails>(
"ContactDetails")); }
}
private ObjectSet<ContactDetails> _contactDetails;
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:
int? x = null;
int y = x ?? -1;
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
.
Summary
Let's sum up, the null-coalescing operator is a very simple operator that can be very helpful in null
checking scenarios.