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();
MyClass
should provide apublic static readonly
member of aEmpty
value of its type. SeeString.Empty
on MSDN.??=
operator?