Friday, 4 September 2009

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


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 ).

These Conditional and Null-Coalescing Operators aren't the most self-describing operators :), but I do love programming in C#!

1 comment:

Gabe Co Hadwin said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.