HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C#VariablesData TypesOperatorsStringsListsConditions (if / else)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 List & Dictionary
🔀 Condition & Loop
🧩 Function
C#›Conditions (if / else)

Conditions (if / else)

Making decisions with if-else if-else; conditions in parentheses, blocks in curly braces.

Simple enough for a 5-year-old to understand

decision with if

Example code
1
using System;
2
int age = 20;
3
if (age >= 18) {
The condition is inside parentheses.
ConditionThe condition is inside parentheses.
4
Console.WriteLine("Adult");
Runs if true.
Output / InputRuns if true.
5
} else {
6
Console.WriteLine("Child");
7
}
ConditionOutput / Input
💡 Hint: The condition is written inside parentheses ( ), and the block inside curly brackets { }.

About this topic

Conditions give programs the ability to make decisions. In C#, a condition expression MUST be a bool — numbers or objects cannot be written directly as conditions. This strictness makes classic bugs like accidental assignment impossible right from the start.

C#'s strength lies in pattern matching. The switch structure can perform not only constant comparisons, but also type checks, range checks, and condition combinations. The switch expression format, on the other hand, returns a value and makes writing break unnecessary.

In modern C# code, using a switch expression instead of long if-else chains is both shorter and safer: since every case is required to return a value, leaving out a case is caught by the compiler.

What you will learn

  • the if, else if, and else structure
  • the difference between switch expression and switch statement
  • Pattern matching and type patterns
  • The ternary conditional operator
  • Why the condition has to be a bool

When to use?

If you are comparing a value against many possibilities, a switch expression is the most readable way. If you are doing a type check, a type pattern is used; if you are doing a range check, a relational pattern is used.

You use conditions in input validation, authorization checks, and business rules. For null checks, null-conditional access and null-coalescing provide a solution without needing an if block.

Common mistakes

Wrong

int count = 5;
if (count) {
    Console.WriteLine("exists");
}

C# expects a bool in the condition, it does not accept numbers; it gives "error CS0029: Cannot implicitly convert type 'int' to 'bool'". This strictness also prevents you from accidentally making an assignment with a single equals sign.

Correct

int count = 5;
if (count > 0) {
    Console.WriteLine("exists");
}

Wrong

switch (role) {
    case "admin":
        Console.WriteLine("administrator");
    case "user":
        Console.WriteLine("user");
        break;
}

Unlike Java, C# does NOT allow fall-through and gives "error CS0163: Control cannot fall through from one case label to another". This is an error caught by the compiler — but the switch expression format completely eliminates this issue.

Correct

Console.WriteLine(role switch {
    "admin" => "administrator",
    "user" => "user",
    _ => "unknown"
});

Wrong

if (score > 50)
    Console.WriteLine("passed");
    Console.WriteLine("congratulations");

Since there are no curly braces, only the FIRST line belongs to the condition; the second line runs in every case. Indentation is misleading, C# does not look at indentation. You do not get an error message, the code behaves incorrectly in silence.

Correct

if (score > 50) {
    Console.WriteLine("passed");
    Console.WriteLine("congratulations");
}

Frequently asked questions

What is the difference between a switch expression and a switch statement?

The statement format is the classic structure: case labels, break, and code blocks. The expression format uses arrow syntax, returns a VALUE, and can be assigned. The expression format is shorter, does not require break, and the compiler warns about missing cases.

What does pattern matching do?

It allows you to compare a value not just by equality but also by its structure: by its type, by its range, by the values of its properties. It reduces long if-else chains into a single readable switch expression and is one of C#'s most powerful features.

Should I write curly braces even on a single line?

Yes. Without parentheses, only the first line belongs to the condition; when a second line is added to the block months later, the code silently breaks. This is a classic class of bugs experienced in real projects.

Summary

In C#, a condition must be a bool, and the compiler does not allow fall-through in switch. A pattern-matching switch expression is the modern equivalent of long if-else chains, and curly braces must be written even for single-line blocks.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code