Understanding the if-else Statement in C#: Syntax and Usage Explained

Rumman Ansari   Software Engineer   2024-07-05 09:13:56   6020  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

if-else Statement

C# also provides for a second part to the if statement, that is else. The else statement must follow if or else if statement. Also, else statement can appear only one time in a if-else statement chain.

Syntax:

if(boolean expression)
{
// execute this code block if expression evalutes to true
}
else
{
// always execute this code block when above if expression is false
}

As you can see in the above syntax, the else stament cannot contain any expression. The code block that follows else statement will always be executed, when the 'if' condition evalutes to be false.

Example: if else


int i = 10, j = 20;

if (i > j)
{
    Console.WriteLine("i is greater than j");
}
else
{
    Console.WriteLine("i is either equal to or less than j");
}

Output


  i is either equal to or less than j



Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.