Thursday, July 26, 2012

Inline, nested if statements

The ?: operator was something I had to get used to when I first saw it. I allows you to define a conditional if statement on a single line with a build in assignment. This compacts a lot of code and once you get used to it it's quite readable.


var <result> = <if-condition> ? <true value> : <false value>;


This can, among other things, be used to translate values. In the following s will contain the text "Small" if i is less than 3, otherwise "Not Small"


int? i = 4;
string s = i<3 ? "Small" : "Not small";

Whatever is behind the colon, you can replace with a new inline if statement. Now its an if/else if/else statement on a single line.

string s = i<3 ? "Small" : i==3 ? "Three" : i>3 ? "Large" : "Not a Number";

Which gives the same result as.

string s;
if(i<3){
   s = "Small";
}else if(i==3){
   s = "Three";
}else if(i>3){
   s = "Large";
}else{
   s = "Not a Number";
}

This is even better when used in lambda expressions as a "standard" lambda expression only allows one statement. 

Console.WriteLine(
   GetInts().Select(i=>i<3?"Small":i==3?"Three":i>3?"Large":"Not a Number")
            .Aggregate((x, y) => x + "\n" + y)
);