Lesson 7 of 24

In progress

Course progress

C# and .NET

Conditions and branching

Write if, else if and else, combine conditions safely, and use early returns to keep a method flat.

C# conditions are strict: the expression must be a bool. That small rule removes the accidental assignment that other C-family languages accept, and it makes the intent visible in the type.

What you will learn

  • Write branching logic in the order it is evaluated.
  • Combine conditions with short-circuit operators.
  • Flatten nested branches with guards.

The shape

int score = 78;
if (score >= 90)
{
Console.WriteLine("A");
}
else if (score >= 80)
{
Console.WriteLine("B");
}
else if (score >= 70)
{
Console.WriteLine("C");
}
else
{
Console.WriteLine("Below C");
}

Branches are tested in order and the first true one runs. Writing score >= 70 first would label a 95 as a C, so the order is part of the logic rather than formatting.

Braces are optional for a single statement and should still be written. Adding a second line later without braces is a classic source of a bug that looks like a formatting change.

Comparison and string equality

string input = "yes";
if (input.Equals("yes", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("confirmed");
}

== on strings compares content, so input == "yes" works. When case or culture should be ignored, Equals with a StringComparison says so explicitly and avoids an allocation from ToLower.

Null safety: input.Equals(...) throws if input is null. Use string.Equals(input, "yes", ...) or a null check first:

if (string.Equals(input, "yes", StringComparison.OrdinalIgnoreCase))

For numbers, == is exact. For double, arithmetic makes exact comparison unreliable, so compare with a tolerance: Math.Abs(a - b) < 1e-9. For decimal, exact comparison is appropriate because the type is decimal.

Combining conditions

bool member = true;
bool coupon = false;
decimal total = 1200m;
bool discount = (member || coupon) && total >= 1000m;

&& binds tighter than ||, so the parentheses above express "member or coupon, and a minimum total". Without them the meaning changes to "member, or coupon and the minimum".

Short-circuit evaluation is what makes null checks safe:

if (name is not null && name.Length > 0)
{
Console.WriteLine(name);
}

The second operand runs only when the first is true, so name is never dereferenced when null. Reverse the order and the guard is useless.

Guards and early return

static string Check(string? user, bool active, bool admin)
{
if (user is null) return "no user";
if (!active) return "inactive";
if (admin) return "full access";
return "limited access";
}

Each guard states one rule and leaves. The nested alternative makes the reader track several conditions at once, and the happy path ends up indented three levels.

Expression-bodied methods with => make the same idea shorter when each branch is a single expression:

static string Size(decimal total) =>
total >= 5000m ? "bulk" : total >= 1000m ? "large" : "small";

Nested ternaries are hard to read; use a switch expression when there are more than two outcomes.

Pattern matching in conditions

object value = 42;
if (value is int number && number > 10)
{
Console.WriteLine($"large number: {number}");
}
else if (value is string text)
{
Console.WriteLine($"text of length {text.Length}");
}

is with a type and a variable tests and assigns in one step, and the variable exists only where the test succeeded. That replaces a cast that could throw and a second null check.

Common patterns

// range
if (age is >= 18 and <= 65) { }
// membership
if (role is "admin" or "owner") { }
// negation
if (status is not "paid") { }

Pattern combinators and, or and not read closer to the requirement than the operator equivalents, and they work on constants, types and ranges.

Reading a condition aloud

A condition is easier to check when it reads as a sentence. if (member || coupon) && total >= 1000m becomes "if the customer is a member or has a coupon, and the total is at least a thousand". If the sentence needs a comma and a second clause, the expression is probably doing too much and deserves a named local.

That practice catches real bugs. The requirement usually has a natural grouping, and an expression that forces an unnatural reading is often grouped wrongly, which is exactly the kind of mistake that survives review because the code looks plausible.

Formatting and readability

Keep the condition on one line where possible, put the body on its own lines, and avoid assignments inside conditions. C# allows an assignment inside a condition only when it returns bool, which is rare enough to be surprising.

A long condition is a candidate for a named local:

bool eligible = member && total >= 1000m && !blocked;
if (eligible) { ... }

The local names the rule, and the if becomes trivial. That is usually worth one extra line.

Writing if (count = 0) expecting a comparison. C# rejects it because an int assignment is not a bool, which turns a silent bug into a compile error.

Write a shipping charge method: 0 for members, 49 for orders of 500 or more, 99 otherwise, and 0 for an empty order. Test four cases.

Show solution
static decimal Shipping(decimal total, int items, bool member) { if (items == 0) return 0m; if (member) return 0m; if (total >= 500m) return 49m; return 99m; } Console.WriteLine(Shipping(0m, 0, false)); // 0 Console.WriteLine(Shipping(200m, 2, true)); // 0 Console.WriteLine(Shipping(600m, 3, false)); // 49 Console.WriteLine(Shipping(100m, 1, false)); // 99

The guards run in order of importance: an empty order beats membership, which beats the total. Returning early keeps each rule visible and makes the four cases easy to trace.

Recap

  • Conditions must be bool, and branches run in the order written.
  • && short-circuits, so null checks belong first.
  • Early returns and pattern combinators keep branching flat and readable.

Next, switch expressions, which replace long else if chains over the same value.

Can an if condition span lines?
Yes. C# ignores newlines inside an expression, so a long condition can be broken across lines.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.