Does the compiler optimize the Null Coalescing operator when used for self assignment?

Viewed 236

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?

2 Answers
Related