If-else statements

If-else statements

You can use if statements to run code statement only if certain conditions are met. Here is an example:

var myNum = (93 + 41) / 12;
if (myNum == 11)
{
Console.WriteLine("They are equal!");
}


Inside the () beside if, you should specify a boolean expression. If the expression is true, the code inside { } is executed. In this case, since myNum is equal to 11, They are equal! is printed.

If the condition is false, nothing happens! For example, since 10 is not greater than 11, Print me! will not show up to the console.

var happy = 10;
if (happy > 11)
{
Console.WriteLine("Print me!");
}


Use else to tell the computer what to do if the condition is false. In this example, now I got printed instead! will be printed to the console.

var happy = 10;
if (happy > 11)
{
Console.WriteLine("Print me!");
}
else
{
}


You can chain many cases together using else if. Note that when using else if, only the first case will be evaluated. For example, in the following code snippet, Statement 1 will be printed. We will skip the check that sad == 4 and Statement 2 will not be printed, even though sad == 4 is true.

var sad = 4;
{
Console.WriteLine("Statement 1");
}
{
Console.WriteLine("Statement 2");
}
else
{
Console.WriteLine("Statement 3");
}


You can also place if statements inside other if statements for some interesting behavior:

var num1 = 10;
var num2 = 20;
if (num1 < num2)
{
if (num2 < 30)
{
Console.WriteLine("Hello!");
}
else
{
Console.WriteLine("Hola!");
}
}