Friday, 6 September 2013

Instantiating Null Objects with ?? Operator

Instantiating Null Objects with ?? Operator

Consider the following typical scenario:
if(anObject == null)
{
anObject = new AClass();
}
I'm wondering what is thought of the following replacement using the ??
operator:
anObject = anObject ?? new AClass();
I'm not sure whether I should be using the second form. It seems like a
nice shorthand, but the anObject = anObject 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!"?

No comments:

Post a Comment