if, else & Conditions
Programs become useful when they can make decisions: give a discount only to students, allow cash withdrawal only in multiples of Rs 100, show "seat" or "seats" depending on the count. In C#, the if statement runs code only when a condition is true.
In this lesson you will write if, else if and else chains, combine conditions, use the short ?: operator for simple choices, and learn the mistakes that make conditions silently go wrong.
if and else
An if statement has a condition in brackets, which must be a bool, followed by a block. An optional else block runs when the condition is false.
int balance = 5000;
int amount = 2500;
if (amount <= balance)
{
balance -= amount;
Console.WriteLine($"Please collect Rs {amount}.");
}
else
{
Console.WriteLine("Insufficient balance.");
}
Console.WriteLine($"Balance: Rs {balance}");Please collect Rs 2500. Balance: Rs 2500
The condition must really be a bool. In C, if (x) works with a number; in C# it is a compile error. Write the comparison you mean, for example if (x != 0).
else if chains
When there are more than two possibilities, chain conditions with else if. C# checks them from top to bottom and runs only the first block whose condition is true. Everything after it is skipped.
int marks = 67;
if (marks >= 90)
{
Console.WriteLine("Grade A+");
}
else if (marks >= 75)
{
Console.WriteLine("Grade A");
}
else if (marks >= 60)
{
Console.WriteLine("Grade B");
}
else if (marks >= 40)
{
Console.WriteLine("Grade C");
}
else
{
Console.WriteLine("Needs improvement");
}Grade B
Because the checks run in order, the second condition does not need to say marks >= 75 && marks < 90: if marks were 90 or more, the first block would already have run. This is why the order of an else if chain matters. If you put marks >= 40 first, every passing student would get Grade C.
Combining conditions
Use && (and), || (or) and ! (not) to build bigger conditions. Brackets make mixed conditions easier to read and remove any doubt about the order.
int age = 62;
bool isWoman = true;
bool isStudent = false;
decimal fare = 1240m;
decimal discount;
if (age >= 60 && isWoman)
{
discount = 0.50m;
}
else if (age >= 60 || isStudent)
{
discount = 0.25m;
}
else
{
discount = 0m;
}
decimal toPay = fare - fare * discount;
Console.WriteLine($"Discount: {discount * 100:F0}%");
Console.WriteLine($"To pay: Rs {toPay:F2}");
int year = 2028;
bool isLeap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
Console.WriteLine($"{year} is a leap year: {isLeap}");Discount: 50% To pay: Rs 620.00 2028 is a leap year: True
The concession rates are invented for the example. Notice that discount is declared without a value but assigned in every branch. The compiler checks this: if one branch forgot to assign it, using discount later would be error CS0165.
The leap-year rule shows how brackets group a condition: a year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400. .NET also has DateTime.IsLeapYear(year) ready-made.
The conditional operator ?:
For a simple choice between two values, the conditional operator (often called the ternary operator) is shorter than a full if. It reads: condition ? value if true : value if false.
int seatsLeft = 1;
string word = seatsLeft == 1 ? "seat" : "seats";
Console.WriteLine($"{seatsLeft} {word} left in the Vande Bharat");
int temperature = 43;
Console.WriteLine(temperature > 40 ? "Heatwave alert for Jaipur" : "Normal day");
int runs = 98;
string message = runs >= 100 ? "Century!" : $"{100 - runs} runs to a century";
Console.WriteLine(message);1 seat left in the Vande Bharat Heatwave alert for Jaipur 2 runs to a century
Use ?: when both sides are short values. If either side needs several statements, or if you are tempted to nest one ?: inside another, write a normal if instead.
Checking for null with is
Some values may be null, meaning "no value", such as the result of Console.ReadLine(). The clearest way to test for that is the is null and is not null patterns:
string? coupon = null;
if (coupon is null)
{
Console.WriteLine("No coupon applied.");
}
coupon = "DIWALI10";
if (coupon is not null && coupon.StartsWith("DIWALI"))
{
Console.WriteLine("Festival discount: 10% off");
}No coupon applied. Festival discount: 10% off
The order inside && matters here. Because && short-circuits, coupon.StartsWith runs only when coupon is not null, so the program can never crash with a NullReferenceException at that line. x == null also works and you will see it in older code, but is null cannot be changed by a class's custom == operator, so it is always a true null check.
Common mistakes
- A semicolon after the condition.
if (marks >= 40);ends theifimmediately, so the block below always runs. The compiler warns withCS0642: Possible mistaken empty statement. - Using
=instead of==.if (age = 18)does not compile in C#, which saves you from a classic C bug. - Wrong order in an
else ifchain. Put the most specific or strictest condition first. - Comparing
doublevalues with==.0.1 + 0.2 == 0.3isfalse. Compare with a small tolerance, or usedecimal. - Case-sensitive text checks.
city == "pune"is false for"Pune". Usestring.Equals(city, "pune", StringComparison.OrdinalIgnoreCase).
Key points
if (condition) { ... } else { ... }runs one of two blocks; the condition must be abool.- In an
else ifchain only the first true branch runs, so order matters. - Combine conditions with
&&,||and!;&&and||short-circuit. condition ? a : bpicks between two values in one expression.- Use
is nullandis not nullto check for null safely. - Always use braces, and watch out for a stray semicolon after
if (...).
Exercise
An electricity board in Rohtak charges per unit like this (rates invented for practice): the first 100 units at Rs 3, the next 100 units (101 to 200) at Rs 5, and every unit above 200 at Rs 7. Customers using more than 300 units pay an extra fixed charge of Rs 150. Write a program that calculates the bill for units = 260 and prints it. Then test your logic mentally with 80 and 350 units.
Show solution
int units = 260;
int bill;
if (units <= 100)
{
bill = units * 3;
}
else if (units <= 200)
{
bill = 100 * 3 + (units - 100) * 5;
}
else
{
bill = 100 * 3 + 100 * 5 + (units - 200) * 7;
}
if (units > 300)
{
bill += 150;
}
Console.WriteLine($"Units: {units}, Bill: Rs {bill}");Units: 260, Bill: Rs 1220
For 260 units: 300 + 500 + 60 x 7 = 1220. For 80 units the bill is 240. For 350 units it is 300 + 500 + 1050 + 150 = 2000. The extra charge is a separate if, not part of the chain, because it applies on top of the slab amount.
Quick Quiz
1. With int marks = 95;, which grade does the lesson's grading chain print?
Only the first true branch in an else if chain runs.
2. What does string s = n > 0 ? "positive" : "not positive"; do when n is 0?
0 > 0 is false, so the value after the colon is used.
3. Why is if (name is not null && name.Length > 3) safe even when name is null?
Short-circuit evaluation skips name.Length when name is null.
4. What is wrong with if (total > 500); { Console.WriteLine("Free delivery"); }?
The ; is an empty statement that belongs to the if; the block that follows always runs.
Learn C# with a mentor
Free lessons get you started. Our Programming & Software Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
