C# : conditional statements

5 May

Like all other programming languages, c sharp conditional statements are used to control the flow of the application. True condition can take you to one direction while false to other. Conditional statements can be

if(condition) {

// statements

}

Before the block of the code in the {} executed, the condition must evaluate to boolean value true. If condition goes wrong the code inside the parenthesis is ignored.

Another very good example can be

if (condition) {

// statements

} else {

// statements

}

In this example if condition become true the code in the first block get executed, otherwise pointer goes to the else part and execute the code of it.

You can make this more general as

if (condition1) {

// code to be executed

} else if(condition2) {

// code executed if condtion2 become true.

} else {

// code of else part.

}

In the above example, first condition1 is checked, if false condition2 is checked. If that is false too the code in the else statement is executed.

The if-else statements can be nested as

if(condition) {

if(inner_condtion) {

// code

} else {

// code

}

}

just play with these if else and see how the code is executed.

In addition to the if-else statements, switch statement can also play a very important role in the flow of our application. The general syntax of the switch statement is

switch(expression)

{

case 1:

// code to be executed.

break;

case 2:

// code to be executed.

break;

default:

// default code is executed.

break;

}

In switch statement every case is checked, if any of the case is true, then the code that follows the case statement is executed. If none of the case statement becomes true, then the code following the default keyword is executed.

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

%d bloggers like this: