← Back to C# Course | Chapter 4: Control Flow | Lesson 1 of 7

if / else

if and else let a program choose what to do, like 'if it is cold, wear a coat, else wear a t-shirt'. The code in a block runs only when its question is true.

In this page:

  1. if / else
Syntax
csharp
if (condition1)
{
    // ...
}
else if (condition2)
{
    // ...
}
else
{
    // none matched
}

if / else

An if statement runs a block only when its condition is true; an optional else runs when it's false. else if chains let you test multiple conditions in order, stopping at the first match.

Braces are optional for single statements but recommended for clarity.

Note: Chain conditions with else if instead of nesting separate if blocks.

Example: if / else

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int score = 72;

        if (score >= 90)
            Console.WriteLine("A");
        else if (score >= 70)
            Console.WriteLine("B");
        else
            Console.WriteLine("C");
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing if (x = 5) with a single equals sign, which is an assignment and only compiles when the assigned value is a bool.
  2. Putting a semicolon after the condition, if (x > 0);, so the body always runs.
  3. Omitting braces so only the first statement after if belongs to it.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.