C# If condition

The if statement checks a given condition (which is an expression that evaluates to true or false) and, based on the result of this evaluation, it determines which block of code to execute.

If the condition is true, the block of code inside the if statement is executed; if the condition is false, the code inside the if block is skipped, and the program continues executing the next instructions.

Syntax:


if (condition)
{
    // Code to execute if condition is true
}

Explanation:

  • condition: This is an expression that evaluates to a boolean value (true or false).
  • The code inside the curly braces {} will execute only if the condition is true.

Example:


using System;

class Example
{
    static void Main()
    {
        int age = 18;
        // Checking if the person is eligible to vote
        if (age >= 18)
        {
            Console.WriteLine("You are eligible to vote.");
        }
    }
}

Explanation:

  1. Condition: age >= 18 is the condition being checked.
  2. Since age is 18, which is equal to 18, the condition evaluates to true.

Output:

You are eligible to vote.

Example: If number is positive


using System;

class Example
{
    static void Main()
    {
        int number = 15;
        // Checking if the number is positive
        if (number > 0)
        {
            Console.WriteLine("Number is positive");
        }
    }
}

Explanation:

  • Condition: number >= 0 is the condition being checked.
  • Since number is greater than 0, then condition evaluates to true.

Output:

Number is positive.