# if-then-(else)
if-then construct is the most common conditional statement. It looks like this,
if (boolean expression)
{
// if boolean expression evaluates to True
}
1
2
3
4
2
3
4
If the condition is true then the body of the if statement is run.
You can also use else.
if (boolean expression)
{
// if boolean expression evaluates to True
}
else
{
// if boolean expression evaluates to False
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
If the condition is false then the body of the else statement is run. Using else is optional.
# 👍 Best Practice
Always enclose if and else body in braces {}
if (num < 10)
{
Console.WriteLine($"{num} is less than 10");
}
else
{
Console.WriteLine($"{num} is greater than 10");
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 👎 Bad Practice
WARNING
The following style of code is bad. Do not use it.
If your if or else body has a single line then you can remove the enclosing braces {}.
if (num < 10)
Console.WriteLine($"{num} is less than 10");
else
Console.WriteLine($"{num} is greater than 10");
1
2
3
4
2
3
4
But never write a if and else body without braces.