Digital Colony!

Single Line If Statement in C#

Here is a standard if ... then statement in C# followed by a single line example. Using a single line if statement will reduce the number of lines of code.
if (dayOfTheWeek == "Tuesday")
{
    lunchLocation = "Fuddruckers";
}
else
{
    lunchLocation = "Food Court";
}
And the same example as a single line if ... then statement.
lunchLocation = (dayOfTheWeek == "Tuesday") ? "Fuddruckers" : "Food Court";

Labels:

AddThis Social Bookmark Button

1 Comments:

Anonymous Sam Goody said...

It's useful for a lot more than just shortening your code.

Among it's many uses, it can be put where a conditional cannot. For example if you need to evaluate whether an variable is greater than 5, and that variable is chosen via a flag, it can be done with:

if (flag == 'a' ? num1 : num2 > 5)....

Also, single line ifs - also called ternary operators can be stacked, even in C#.

I wrote a rather extensive article on this on my blog, but the blog is down now :(. Hopefully will get it back up soon

5/12/2008 12:57 AM

 

Post a Comment

 

Digital Colony Copyright © 1999-2008 XHTML   508
This site uses Blogger, which is not 100% XHTML compliant.
Try...Catch Disclaimer: For brevity many examples do not include error handling. That is your responsibility.