The ifâelse statement in C# is used for decision making. It allows a program to execute different blocks of code based on whether a given condition is true or false.
Since C# is a strongly typed language, the condition
used inside an if statement must always return a
boolean value.
if (condition)
{
// Executes when condition is true
}
else
{
// Executes when condition is false
}
int age = 20;
if (age >= 18)
{
Console.WriteLine("Eligible to vote");
}
else
{
Console.WriteLine("Not eligible to vote");
}
When multiple conditions are involved, the else if ladder is used. Conditions are checked from top to bottom.
int marks = 72;
if (marks >= 90)
{
Console.WriteLine("Grade A");
}
else if (marks >= 60)
{
Console.WriteLine("Grade B");
}
else
{
Console.WriteLine("Grade C");
}
int salary = 60000;
int experience = 3;
if (salary > 50000 && experience >= 2)
{
Console.WriteLine("Eligible for promotion");
}
else
{
Console.WriteLine("Not eligible");
}
The ternary operator is a compact form of ifâelse used for simple decisions.
int number = 7;
string result = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine(result);
= instead of == in conditions{ }The ifâelse statement is one of the most fundamental control structures in C#. Mastering it is essential for writing logical, readable, and efficient programs.