Summary: in this tutorial, you’ll learn how to use the C# if else
statement to execute a block when a condition is true
and another block otherwise.
Introduction to the C# if else statement
In practice, you often want to execute a block when a condition is true
and execute another block otherwise. In this case, you need to use the if else
statement.
The following illustrates the syntax of the if else
statement:
if (condition)
{
// if statements
}
else
{
// else statements
}
Code language: C# (cs)
In this syntax, the if else
statement evaluates the condition
. If the condition
is true
, it’ll execute the if block. Otherwise, the if else
statement executes the else
block.
The following flowchart illustrates how the if else
statement works:
C# if else statement examples
Let’s take some examples of using the if else
statement.
1) Simple C# if else statement examples
The following example uses the if else
statement to show a message when the condition
is "sunny"
:
string condition = "sunny";
if (condition == "sunny")
{
Console.WriteLine("Let's go outside.");
}
else
{
Console.WriteLine("Just stay home.");
}
Code language: C# (cs)
Output:
Let's go outside.
Code language: C# (cs)
In this example, the condition is "sunny"
. Therefore, you’ll see the message "Let's go outside."
in the output.
The following example changes the condition
to "rainy"
:
string condition = "rainy";
if (condition == "sunny")
{
Console.WriteLine("Let's go outside.");
}
else
{
Console.WriteLine("Just stay home.");
}
Code language: C# (cs)
Output:
Just stay home.
Code language: C# (cs)
Since the expression condition == "sunny"
is false
, the else
block executes that shows the message "Just stay home."
to the output.
2) Using if else statement with a complex condition example
The following example uses the if else
statement with a complex condition:
string condition = "sunny";
bool free = true;
if (free & condition == "sunny")
{
Console.WriteLine("Let's go outside.");
}
else
{
Console.WriteLine("Just stay home.");
}
Code language: C# (cs)
Output:
Let's go outside.
Code language: C# (cs)
In this example, the condition
is "sunny"
and the free
is true
.
Because the following expression evaluates to true
:`
free & condition == "sunny"
Code language: C# (cs)
the if
block executes to show the message "Let's go outside."
to the output.
If you change the condition
and/or free
variables to something else that causes the expression evaluates to false
, the else
block will execute. For example:
string condition = "sunny";
bool free = false;
if (free & condition == "sunny")
{
Console.WriteLine("Let's go outside.");
}
else
{
Console.WriteLine("Just stay home.");
}
Code language: C# (cs)
Output:
Just stay home.
Code language: C# (cs)
Summary
- Use the C#
if else
statement to execute a block when a condition istrue
and another block otherwise.