An if statement identifies which statement to run based on the value of a Boolean expression.
Code Example
if
using System;
int age = 30;
if(age == 30)
{
Console.WriteLine("age is 30");
}
Console.WriteLine($"age is {age}");
if … else
using System;
int age = 30;
if(age == 30)
{
Console.WriteLine("age is 30");
}
else
{
Console.WriteLine("age is not 30");
}
Console.WriteLine($"age is {age}");
if … else if … else
using System;
int age = 30;
if(age > 30)
{
Console.WriteLine("age is > 30");
}
else if (age == 30)
{
Console.WriteLine("age is 30");
}
else
{
Console.WriteLine("age is < 30");
}
Key Points
- There is no limit to how many
else ifyou can add to anifclause. - You can use nested if else as well.
- In C#, the expression in the if / else if clause must evaluate to a
Boolean. It is not possible to test an integer directly.
One Reply to “#8 – C# if else Statement”