My C# Null-Conditional and Null-Coalescing Operator Friends

The null-conditional operator introduced in C# 6.0 makes me happy. Yes I know C# 7.0 is out now in VS 2017, but I've been on client projects using VS 2013 for a while now so C# 6.0 still seems exciting and fresh to me.

Today I ran across this line in my code that uses the ternary operator. Now the ternary operator has been a friend of mine since I learned C. So at least I didn't have to use an if-else statement.

string name = source != null ? source.DisplayName : string.Empty;

When I saw this code today, it occurred to me that I can rewrite it using my new friend the null-conditional operator and combine it with an old C# friend of mine the null-coalescing operator:

string name = source?.DisplayName ?? string.Empty;​

Of course in the rewrite if source.DisplayName is null then name will be set to empty string. While it would be set to null in the code that uses the ternary operator. Hey look I fixed a bug too!

So the null-conditional operator is my new best friend. And the null-coalescing operator is an excellent friend when used along with it.​

Comments

Popular posts from this blog

API Authorization for HTTP triggered Azure Functions with OIDC and OAuth 2.0

Duplicate Detection for Service Bus output binding in Azure Functions