Search code examples
c#if-statementnullnull-coalescing-operator

?? null-coalescing operator vs if == null


When instantiating null objects with ?? null-coalescing operator is there any performance difference, additional cycles, etc. vs simple if == null statement? Any effect from assigning object to itself?

RedColorBrush = RedColorBrush ?? new SolidColorBrush(renderTarget, Color.Red);

vs

if (RedColorBrush == null)
{
    RedColorBrush = new SolidColorBrush(renderTarget, Color.Red);
}

Solution

  • According to this post the ?? and ?: operators might actual be faster (though not by much) because these operators actually evaluate as a value, where as, an if statement directs a different line of path, and might result in creating another variable that could have been avoided.

    Also, the ?? operator is almost like a specialized case of the ?:

    Edit: It also just looks cleaner and is quicker to type. I for one hate having to retype the same things again and again, which is why I like C#, because it gives a lot of options for shorthand.