The New Null-Coelscing Operator in C# 2.0

There is a new operator in town. It is called Null-Coelscing operator. The operator takes two operands, if the operand on the left is not null then it is returned else the operator on the right is returned. Check out the code examples below:

static void Main(string[] args)
        {
            
string userName = null;
            Console.WriteLine(userName ?? "AzamSharp"); 
// displays AzamSharp 

 //           int someNumber = 10;
   //         Console.WriteLine(someNumber ?? 30); // compile
   //time error ?? cannot be applied to value types
 
            
int? number = null;
            Console.WriteLine(number ?? 10); 
// displays 10 

            
User user = null;

            Console.WriteLine(user ?? 
new User()); // new user is created 

        
}

Using the Null-Coelscing operator saves you typing tons of lines in which you check for the null value and take the action based on the result.

Pretty cool right!  

powered by IMHO 1.3

Print | posted @ Friday, June 02, 2006 10:18 PM

Twitter