These two code blocks are functionally the same
if (myObj == null)
{
myObj = new MyObj();
}
and
myObj = myObj ?? new MyObj();
However, the one using the null coalescing operator does an unnecessary assignment in the case where myObj is not null. But then I thought maybe the compiler optimizes these self assignments. Does anyone know if the compiler will notice what is going on and essentially convert the bottom snippet into the top one?
For comparison purposes, I tried compiling both
and
inside of the
Mainmethod. (I am using MonoDevelop 2.4 on Mono 2.6.7)If the code were optimized as expected, we should see similar IL being generated. Here is the IL for the first version of
Main:and for the second version:
So the first version (using the null-coalescing operator) has generated slightly more IL.
But there are two things to note about this: