Menu

C# if else: else if Chains, Conditions and Common Mistakes

How if, else if and else work in C#: why conditions must be bool, combining tests with &&, || and !, when braces matter, guard clauses instead of deep nesting, and the = versus == and stray semicolon bugs.

This page includes runnable editors - edit, run, and see output instantly.

An if statement runs a block of code only when a condition is true. else if adds more tests, and else catches everything the tests did not.

Output:

Order 120: shipping 0
Order 75.50: shipping 4.99
Order 20: shipping 9.99

The conditions are checked from top to bottom and the first true one wins. An order of 120 matches >= 100 and never reaches the >= 50 test, which is why the most specific condition goes first. else if is not a separate keyword: it is an else whose body is another if, so there is no elseif or elif in C#.

Conditions Must Be bool

C# never treats a number, a string or an object as true or false. The expression in parentheses must have type bool:

int count = 3;
if (count)          // error CS0029: Cannot implicitly convert type 'int' to 'bool'
if (count > 0)      // correct
if (name)           // error: a string is not a bool either
if (name != null)   // correct

This removes a whole family of bugs from C and JavaScript, where 0, "" and null silently count as false. The price is that you write the comparison out every time, which also makes the intent visible to the next reader.

Combining Conditions with &&, || and !

&& (and), || (or) and ! (not) combine boolean tests. && and || short-circuit: the right side runs only if the left side did not already decide the answer.

Output:

maya: welcome
invalid or banned account
invalid or banned account
omar: age 9 rejected
invalid or banned account

The null call is safe because of short-circuiting: once username != null is false, username.Length is never evaluated, so no NullReferenceException. Swap the order to username.Length >= 3 && username != null and the same call crashes.

&& binds tighter than ||, so a || b && c means a || (b && c). Add parentheses whenever you mix the two; the compiler does not need them, but readers do. The single-character & and | also work on bool, but they always evaluate both sides. Use them only when the right side has a side effect that must happen.

Braces and the One-Statement Rule

Braces are optional when a branch holds a single statement. Without them, only the next statement belongs to the if, whatever the indentation says:

Output:

Reorder email sent
Stock: 12

"Reorder email sent" prints even though stock is fine: the second WriteLine is outside the if, indentation notwithstanding. A one-line guard such as if (x == null) return; is fine without braces; anything that might grow a second line should get them.

A related bug is a semicolon right after the condition. if (stock < 5); ends the if with an empty statement, and the block that follows runs unconditionally. The compiler flags it with warning CS0642, Possible mistaken empty statement, which is worth treating as an error.

= Versus == in a Condition

= assigns, == compares. For most types, writing = by mistake does not compile, because the result of an assignment is the assigned value and an int is not a bool:

int score = 10;
if (score = 100) { }   // error CS0029: Cannot implicitly convert type 'int' to 'bool'

With a bool variable the assignment is itself a bool, so the typo compiles:

Output:

Access granted
isAdmin is now True

The condition overwrote isAdmin and then tested the new value. The compiler warns (CS0665, assignment in a conditional expression is always constant), but the build still succeeds. For bools, skip the comparison altogether: if (isAdmin) and if (!isAdmin) read better and cannot be mistyped this way.

Nested if Versus Guard Clauses

Every level of nesting is another condition the reader has to hold in their head. When each check rejects bad input, return early instead of nesting the happy path inside all of them:

Output:

ordered 2 x keyboard
error: no product
error: quantity must be positive
error: insufficient balance

The nested version of the same method would have three levels of if with the real work in the innermost block and three else branches unwinding at the bottom. With guard clauses, each rule sits next to its error message and the last line is the normal case. The same idea works inside loops with continue.

Declaring Variables in the Condition

A condition can declare a variable that is in scope inside the if. The two common forms are an out var from a TryParse method and the is type pattern:

Output:

42: positive number 42
abc: not a number
-7: number -7, not positive
string of length 5

TryParse returns false instead of throwing on bad input, which makes it the natural fit for an if. The type conversion page covers the parsing methods in detail.

When to Use Something Else

  • Picking one of two values: the conditional operator condition ? a : b is shorter than an if that assigns in both branches.
  • Many branches on one value: a switch statement compares a value against constant cases and is easier to scan than ten else if lines.
  • Mapping a value to a result: a Dictionary lookup replaces a long chain when the branches only differ in data.

Frequently Asked Questions

How do you write else if in C#?

Write else if as two words: if (a) { ... } else if (b) { ... } else { ... }. The conditions are tested top to bottom and only the first true branch runs, so put the most specific test first. There is no elif or elseif keyword.

Why can't I write if (count) in C#?

A C# condition must be of type bool. Unlike C and JavaScript, an int, a string or an object is never converted to true or false, so if (count) fails with CS0029, Cannot implicitly convert type 'int' to 'bool'. Write the test you mean: if (count > 0) or if (name != null).

What is the difference between && and & in an if condition?

&& short-circuits: if the left side is false the right side is never evaluated, which is what makes s != null && s.Length > 0 safe. & on two bools evaluates both sides every time. The same applies to || and |. Use && and || in conditions unless you need the right side's side effect.

Are braces required in a C# if statement?

No. Without braces the if controls exactly one statement. Indenting a second line does not add it to the branch, which is a classic source of bugs, so most style guides recommend braces on every branch.

Can I write an if else on one line in C#?

For choosing a value, use the conditional operator: string label = score >= 50 ? "pass" : "fail";. For running statements, if (x) DoA(); else DoB(); is legal on one line, but it is harder to read and to extend than a braced block.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED