i

ASP.Net A Complete Guide

C# Control Structures

In C# below are three types of control statements:

  • Selection Statements

  • Iteration Statements

  • Jump Statements 

Selection Statements:

Selection statements consist of if, else, switch, and case branching.

If statement: Decides which conditions require to be executed. It has a Boolean condition followed by one or more statements. 

It executes only when the given condition is true.

Syntax:

if (condition)

{

Statement;

}

if …else statement: Else is the variation of if statement, it executes the false condition. Else can be used followed by if statement.

If (condition)

{

Statement;

}

Else

{

Statement;

}

Nested if/ if... else statements:

We can use one if or else if statement inside another if or else if statement(s).

 If (condition)

   {

Statement;

   }

   Else if (condition)

   {

     If (condition)

    {

Statement

    }

   }

 

Switch statement:

The select statement has multiple cases/Condition-based upon the matching condition it select the matching case for execution.

Switch (Condition)

{

Case s:

Statement;

Break;

Case t:

Statement;

Break;

Default:

Statement;

Break;

}

Iteration Statements

 Do Statement: The do repeats the execution of a statement(s) until a given condition is false.

It always executes once before checking the condition. 

Do

{

Statement;

While (statement); for statement: The 'for' statement repeats the execution of a statement until a specified condition is false. 

for (initializer; condition; iterator)

{

Statement;

foreach statement: The "foreach" statement repeats statements for each element of an object collection or array. 

foreach (int element in objectCollection)

{

Statement;

}

while statement: This statement executes a statement(s) while a condition evaluates to true. 

while (statement)

{

Statement;

}

Jump Statements:

break; Stops the executions from the location where we wrote 'break', and passes control to the next statement, if it exists.

continue; continue statement passes control to the next iteration from the current location.

return; It returns control from the current location regardless of the number of statement present below the statement or not.

goto; It is used to transfer the control to the particular location.