C# If–Else Statement

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.

Why Use If–Else?

  • To control program flow
  • To apply business logic
  • To make decisions at runtime
  • Frequently used in real-world applications

Syntax


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

Example 1: Simple If–Else


int age = 20;

if (age >= 18)
{
    Console.WriteLine("Eligible to vote");
}
else
{
    Console.WriteLine("Not eligible to vote");
}
    

If – Else If – Else (Multiple Conditions)

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");
}
    

Using Logical Operators


int salary = 60000;
int experience = 3;

if (salary > 50000 && experience >= 2)
{
    Console.WriteLine("Eligible for promotion");
}
else
{
    Console.WriteLine("Not eligible");
}
    

Short-Hand If–Else (Ternary Operator)

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);
    

Common Mistakes

  • Using = instead of == in conditions
  • Forgetting curly braces
  • Using non-boolean expressions in conditions

Best Practices

  • Always use curly braces { }
  • Keep conditions simple and readable
  • Avoid deeply nested if–else blocks
  • Use ternary operator only for simple logic

Conclusion

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.

C# If–Else Quiz

Q1. Which condition is valid in C#?



Q2. What will be the output?

int x = 5;
if (x > 10)
    Console.Write("A");
else
    Console.Write("B");
        


Q3. Which operator is used for short-hand if–else?


C# Introduction C# Variables & Keywords C# Data Types C# If Else Statement C# Loops C# Comments C# Type Casting C# User Input C# Operators C# Math C# String C# OOP Concepts C# Classes and Objects C# Multiple Classes and Objects C# Class Members C# Constructors C# Access Modifiers