Thursday, 17 September 2015

How to Resolve null values in C Sharp

How to Resolve null values in C #

Say you have a method which accepts a string parameter. The method may need to handle null values in some way. One strategy is to validate the parameter and throw an exception

Another strategy is to provide some default value with an if-else statement:

This can be greatly simplified with the ternary operator:

An even simpler solution is by using the null-coalescing operator ?? :

This statement is equal to the first if-else solution but it’s a lot more elegant and concise.
You can use this technique with any nullable type of course, not just strings. The ?? operator can even be chained:


Post a Comment