Search code examples
c#refactoringsimplifynull-coalescing-operator

Is using the null-coalescing operator in C# always redunant if defaulting to null?


In C# is

x = y ?? null;

always equivalent to

x = y;

if both x and y are nullable types?

I can't think of a reason why the first line of code would ever be needed over the second.


Solution

  • Yes, writing the line

    x = y ?? null;
    

    Seems silly, since the expression will return null if y is null (so basically returning y) and y otherwise.

    Remember that the null-coalescing operator is functionally the same as writing:

    x = y != null ? y : <whatever operand>
    

    Or, of course (for those not familiar with the ternary operator):

    if (y != null)
       x = y;
    else
       x = <whatever operand>;
    

    In either case, using the null as the second argument has no utility whatsoever. You might as well just assign the variable, as noted in your post.