#8 – C# if else Statement

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 if you can add to an if clause.
  • 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”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.