Search code examples
c#.netasp.netnull-coalescing-operator

Coalesce operator in C#?


I think i remember seeing something similar to the ?: ternary operator in C# that only had two parts to it and would return the variable value if it wasn't null and a default value if it was. Something like this:

tb_MyTextBox.Text = o.Member ??SOME OPERATOR HERE?? "default";

Basically the equivalent of this:

tb_MyTextBox.Text = o.Member != null ? o.Member : "default";

Does such a thing exist or did I just imagine seeing this somewhere?


Solution

  • Yup:

    tb_myTextBox.Text = o.Member ?? "default";
    

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator