C# Conditional Statements



C# Conditional Statements

Conditional statement in C# used to take decision on based the conditions is true or false.

There are basic five types of conditional statements in C#.

if statement

if – else statement

if – else if – else statement

Nested if statement

switch statement


if statement

if condition – this statement is used when we want to execute a code only one condition must be true.

if condition syntax in C# :

if (condition)
{
// condition is true then code to be executed
}


if – else statement

if-else condition – this statement is used when we want to execute a code in both the condition. if condition is true execute some code, if false execute another code.

if-else condition syntax in C# :

if(condition)
{
// condition is true
}
else
{
// condition is false
}


if – else if – else statement

if-else if-else statement – this statement is used when we want to execute a code if one of multiple condition is true.

if-else if-else statement syntax in C# :

if (condition)
{
// if this condition is true then code to be executed
}
else if (condition)
{
// if this condition is true then code to be executed
}
else if (Condition)
{
// if this condition is true then code to be executed
}
else
{
// all conditions are false then this code to be executed
}


Nested if statement

Nested if else statement – Nested if else statement in C# means, if else statement inside another if else statement.

Nested if else statement syntax in C# :

if(condition1)
{
if(condition2)
{
// execute code when condition1 and condition2 are true
}
else if(condition3)
{
if(condition4)
{
// execute code when condition3 and condition4 are true
}
else
{
// execute code when condition3 is true
// execute code when condition4 is false
}
}
}
else
{
// execute code when conditions1 is false
}


switch statement

switch statement – same as if-else if-else this statement is used we have multiple condition but only one condition true that code will be executed.

switch statement syntax in C# :

switch (a)
{

case statement1:
if a=statement1 then code to be executed;
break;
case statement2:
if a=statement2 then code to be executed;
break;
case statement3:
if a=statement3 then code to be executed;
break;
…….
default:
if “a” is not matches with any statement then code to be executed.
}

Subscribe us

If you liked this c#.net post, then please subscribe to our YouTube Channel for more c#.net video tutorials.

We hope that this asp.net c# tutorial helped you to understand about Conditional Statement in C#.


Next tutorials we will learn all C# statements one by one with an example. Lest’s start with If-Else Statement.


Leave a Reply

Your email address will not be published. Required fields are marked *