OneBite.Dev - Coding blog in a bite size

Use If Conditional Statement In C#

Code snippet for how to Use If Conditional Statement In C# with sample and detail explanation

When programming in C#, it’s often necessary to make decisions and control the program’s flow based on certain conditions. The most common construct to achieve this is by using the if conditional statement.

Code snippet for If Conditional Statement

Here’s a simple example:

int temperature = 27;

if (temperature > 30)
{
    Console.WriteLine("It's hot today!");
}
else if (temperature < 20)
{
    Console.WriteLine("It's cold today!");
}
else
{
    Console.WriteLine("It's a nice day!");
}

Code Explanation for If Conditional Statement

In the code snippet above, we begin by declaring an integer variable named temperature and assigning it a value of 27.

int temperature = 27;

Next, we use the if statement to check whether the temperature is greater than 30.

if (temperature > 30)
{
    Console.WriteLine("It's hot today!");
}

If this condition is met, it will print out “It’s hot today!“. However, if the condition is false, it won’t execute the code in the braces of if instead it will move to the next else if condition.

else if (temperature < 20)
{
    Console.WriteLine("It's cold today!");
}

So, if the temperature is less than 20, it will print “It’s cold today!“. Again, if this condition is not met, it will move to the next else statement.

else
{
    Console.WriteLine("It's a nice day!");
}

Finally, if none of the previous conditions were met, it will execute the else block, printing out “It’s a nice day!“.

This is a basic illustration of using the if conditional statement in C# to control the flow of a program based on different conditions. The if statement evaluates a condition and if this condition is true, it executes a block of code. If it’s false, it moves on to the next else if or else condition.

c-sharp