C# – Instantiating Null Objects with Null-Coalescing Operator

coperators

Consider the following typical scenario:

if(myObject == null) {
    myObject = new myClass();
}

I'm wondering what is thought of the following replacement using the null-coalescing operator:

myObject = myObject ?? new myClass();

I'm not sure whether I should be using the second form. It seems like a nice shorthand, but the myObject = myObject construct at the beginning seems like it could be a bit of a code-smell.

Is this a reasonable thing to do, or is there a better shorthand that I am missing? Or maybe, "It's three lines, get over it!"?

Edit:
As has been mentioned, perhaps calling this a typical scenario is something of an overstatement. I usually find that I encounter this situation when I'm retrieving an entity from a database that has a child reference type property that may or may not be populated yet:

myClass myObject = myClassService.getById(id);
myObject.myChildObject = myObject.myChildObject ?? new myChildClass();

Best Answer

I use the null coalescing operator all of the time. I like the conciseness of it.

I find this operator to be similar in nature to the ternary operator (A ? B : C). It takes a little practice before the reading of it is second nature, but once you're used to it I feel readability improves over the longhand versions.

Also, the situation you describe is only one scenario where the operator is useful. It's also handy to replace constructs like this:

if (value != null)
{
    return value;
}
else
{ 
    return otherValue;
}

or

return value != null ? value : otherValue;

with

return value ?? otherValue;