Conditional C# Syntax

Different ways to write conditional statements in C#:


// IF

if(condition)

{

//Do something

}

// If ELSE

if(condition)

{

// Do something

}

else

{

// if false, do something else

}

// IF, ELSE IF

if(condition1)

{

// Do something

}

else if(condition2)

{

// If not condition 1 and condition 2, do something

}

// Note that you can omit the brackets if you only need to do one action.

if(condition)

CallMethod();

// Need to make a conditional assignment? Shorten it!

string yourString = boolCondition ? "This will be assigned if true" : "This will be assigned if false";

// Switch statements can come in handy if there are many different conditions.

switch(someText)

{

case "1":

// do something

break;// breaks out of switch

case "2":

case "3":

// Do the same thing if someText is "2" or "3", then break out of switch

break;

default:

// Thing to do if nothing matches

}

Note that all the above can be stacked and use in many different ways. Your aim should always be to write elegant and readble code

Advertisements

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