csharp-condicional-if-else

What is and how to use the conditional IF-ELSE in C#

  • 5 min

The if and if-else conditionals are fundamental control structures that allow you to make decisions based on boolean evaluations (true or false).

If you want to learn more, check out the Introduction to Programming Course

The IF Conditional

The if structure evaluates a boolean expression and executes a block of code only if the expression evaluates to true. The basic syntax of an if conditional in C# is:

if (condition)
{
    // Code to execute if the condition is true
}
Copied!

Let’s see it with an example,

int number = 10;

if (number > 5)
{
    Console.WriteLine("The number is greater than 5");
}
Copied!

In this example, the condition number > 5 evaluates to true, so the message “The number is greater than 5” is printed to the console.

The IF ELSE Conditional

The if conditional allows you to add an alternative else block of code that will execute if the if condition is false. The basic syntax is:

if (condition)
{
    // Code to execute if the condition is true
}
else
{
    // Code to execute if the condition is false
}
Copied!

Let’s see it with an example,

int number = 3;

if (number > 5)
{
    Console.WriteLine("The number is greater than 5");
}
else
{
    Console.WriteLine("The number is not greater than 5");
}
Copied!

In this case,

  • The condition number > 5 is false
  • Therefore, the code block inside the else is executed
  • Consequently, “The number is not greater than 5” is printed to the console

The IF ELSE-IF Conditional

To evaluate multiple conditions, you can chain multiple if / else-if / else blocks. This allows evaluating several conditions in sequence until one of them is true.

if (condition1)
{
    // Code to execute if condition1 is true
}
else if (condition2)
{
    // Code to execute if condition1 is false and condition2 is true
}
else
{
    // Code to execute if all previous conditions are false
}
Copied!

Using Logical Operators in Conditionals

To evaluate multiple conditions within a single if, you can use logical operators like && (logical AND) and || (logical OR).

For example, the && operator evaluates to true only if both conditions are true.

int number = 10;

if (number > 5 && number < 15)
{
    Console.WriteLine("The number is between 5 and 15");
}
Copied!

While the || operator evaluates to true if at least one of the conditions is true.

int number = 20;

if (number < 5 || number > 15)
{
    Console.WriteLine("The number is less than 5 or greater than 15");
}
Copied!

Practical Examples