RSS

C# “If Then Else” Shorthand Syntax with “?:” Operator

09 Mar

To do if then else shorthand syntax in C#, the syntax:

condition ? expression_for_true : expression_for_false

Type for condition is bool.

‘expression_for_true’ and ‘expression_for_false’ can be expression that run methods.

When ‘expression_for_false’ is not necessary, set it to original variable. See Example 2.

Example 1

return (MyBlogPosts.Count() != 0) ? System.IO.File.Create("totalPosts.txt") : false;

instead of

if (MyBlogPosts.Count() != 0)
{
    System.IO.File.Create("totalPosts.txt");
}
else
{
    return false;
}

Example 2

string PostsSize = (MyBlogPosts.Count() > 100) ? PostsSize = "Large" : PostsSize;

instead of

string PostsSize = "";
if (MyBlogPosts.Count() > 100)
{
    PostsSize = "Large";
}

Additional resource: http://msdn.microsoft.com/en-us/library/ty67wk28.aspx

About these ads
 
6 Comments

Posted by on March 9, 2011 in Programming

 

Tags: ,

6 responses to “C# “If Then Else” Shorthand Syntax with “?:” Operator

  1. duy

    December 9, 2011 at 9:03 am

    Thanks!

     
  2. adevelopersnotes

    January 24, 2012 at 6:50 am

    Great tip!

     
  3. AaZocco MinDeL

    October 4, 2012 at 4:07 pm

    it’s just an old syntax that had been applied in ms excel. look at the IIF function in excel. Just look likes a twin brother with different parents…. :->

     
  4. Ali Nagori

    August 5, 2013 at 5:14 pm

    this is the better syntax in most rapid form , plus it does reduces the code lines

     
  5. Thé noir

    February 7, 2014 at 8:46 am

    i love this syntax :)

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 38 other followers

%d bloggers like this: