C# Conditional Operator (?:) and Null-Coalescing Operator ( ?? )

Today i will show you the conditional operator which is very helpful for code optimization and very useful for beginners who don’t know about this.

Often times in code you want to assign one variable to another, but only if the variable is not null. If it is null, you want to populate the target variable with another ( perhaps default ) value. The code normally may look like this using the C# Conditional Operator:

string fileName = tempFileName != null ?
tempFileName : "Untitled";

If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“.

This can now be abbreviated as follows using the Null-Coalescing Operator:

string fileName = tempFileName ?? "Untitled";

The logic is the same. If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“.

The Null-Coalescing Operator comes up a lot with nullable types, particular when converting from a nullable type to its value type:

int? count = null; int amount = count ?? default(int);

Since count is null, amount will now be the default value of an integer type ( zero ).

 

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>