0
0
CsharpHow-ToBeginner · 3 min read

How to Use If Else in C#: Simple Guide with Examples

In C#, use the if statement to run code only when a condition is true, and else to run code when it is false. The syntax is if (condition) { ... } else { ... }, where the condition is a true or false check.
📐

Syntax

The if statement checks a condition inside parentheses. If the condition is true, the code inside the first block runs. The optional else block runs if the condition is false.

  • if (condition): Checks if the condition is true.
  • { ... }: Code block to run if true.
  • else: Runs if the if condition is false.
  • { ... }: Code block to run if false.
csharp
if (condition)
{
    // code runs if condition is true
}
else
{
    // code runs if condition is false
}
💻

Example

This example checks if a number is positive or not. It prints a message depending on the number's value.

csharp
using System;

class Program
{
    static void Main()
    {
        int number = 5;

        if (number > 0)
        {
            Console.WriteLine("The number is positive.");
        }
        else
        {
            Console.WriteLine("The number is zero or negative.");
        }
    }
}
Output
The number is positive.
⚠️

Common Pitfalls

Common mistakes include forgetting braces { }, which can cause only one line to be controlled by if or else. Another mistake is using = (assignment) instead of == (comparison) in the condition.

Always use braces to avoid confusion and bugs.

csharp
/* Wrong: missing braces, only first line is controlled */
if (number > 0)
    Console.WriteLine("Positive");
    Console.WriteLine("Checked number"); // runs always

/* Right: braces include both lines */
if (number > 0)
{
    Console.WriteLine("Positive");
    Console.WriteLine("Checked number");
}
📊

Quick Reference

KeywordPurpose
ifChecks a condition and runs code if true
elseRuns code if the if condition is false
{ }Groups multiple statements into a block
==Compares two values for equality
!=Checks if two values are not equal

Key Takeaways

Use if to run code only when a condition is true, else for the opposite case.
Always use braces { } to group code blocks for if and else to avoid bugs.
Use == to compare values inside the if condition, not = which assigns values.
Indent your code inside if and else blocks for better readability.
If else helps your program make decisions based on conditions.