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.


C# If condition – Interview Questions

Q 1: What is if statement?
Ans: It executes code when a condition is true.
Q 2: Syntax of if statement?
Ans: if(condition) { }
Q 3: Can if work without else?
Ans: Yes.
Q 4: What type of expression does if require?
Ans: Boolean expression.
Q 5: Can if be nested?
Ans: Yes.

C# If condition – Objective Questions (MCQs)

Q1. Which keyword is used to start a conditional statement in C#?






Q2. What is the output of the following code?

int a = 10;
if(a > 5)
Console.WriteLine("Yes");






Q3. Which data type must the condition in an if statement evaluate to in C#?






Q4. Which symbol is used to enclose the block of statements for if?






Q5. What happens if the condition in an if statement is false?






Related C# If condition Topics