The if-else statement in C# is a control flow structure used to execute code conditionally. It allows you to check a boolean condition (an expression that evaluates to true or false) and execute different blocks of code depending on whether the condition is true or false.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
Explanation:
condition: This is a boolean expression (an expression that results in true or false), which is evaluated.
If the condition is true, the code inside the if block will execute.
If the condition is false, the code inside the else block will execute.
Example:
using System;
class Example
{
static void Main()
{
int age = 15;
// Checking if the person is eligible to vote
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
} else {
Console.WriteLine("You are not eligible to vote.");
}
}
}
Example: If number is not positive
using System;
class Example
{
static void Main()
{
int number = -20;
// Checking if the number is positive
if (number > 0)
{
Console.WriteLine("Number is positive");
} else {
Console.WriteLine("Number is not positive");
}
}
}
Explanation:
- Condition: number >= 0 is the condition being checked.
- Since number is less than 0, then condition evaluates to false.
Output:
C# if else condition – Interview Questions
Q 1: What is if-else?
Ans: Executes one block if condition is true, otherwise another block.
Q 2: Can else exist without if?
Ans: No.
Q 3: Is else mandatory?
Ans: No.
Q 4: How many else blocks are allowed?
Ans: Only one.
Q 5: Can if-else be nested?
Ans: Yes.
C# if else condition – Objective Questions (MCQs)
Q1. Which keyword is used to provide an alternative block in an if statement?
Q2. What is the output of the following code?
int a = 3;
if(a > 5)
Console.WriteLine("Yes");
else
Console.WriteLine("No");
Q3. Can an if-else statement have multiple else blocks?
Q4. Which of the following is the correct syntax of if-else?
Q5. What type of statement is else in C#?