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:
Number is not positive.