I get a kick when someone sees the coalesce (??) operator for the first time. Usually I get questions like “does that actually compile?”.
The answer is yes, it does compile. Simply stated, the coalesce operator is a binary operator that returns the left hand side value if it is not null, otherwise it returns the right hand side.
Big whoopti doo right? Actually, it is. It’s a nice way to return a default value or ensure that you’re not returning nulls, especially when returning objects whose properties may be accessed.
MyObject.MyObjectProperty.PropertyField
How often have you encountered a null exception because the object returned by MyObjectProperty was null? Below is an example that uses the coalesce operator in a lazy load get property.
public class MyObject
{
public SomeClass MyObjectProperty
{
get
{
return (_localFieldObject ??
(_localFieldObject = new SomeClass()));
}
}
}