In addition to if, C# offers conditional statement if-else. When I explained the if statement, I was saying that the program will execute the instructions only if the if condition is true. What if we wanted to execute a total different condition when and only when that condition is false?
True, we could write another if statement, checking if the condition is false and write the code there, but that would not be very elegant. Instead, we use the conditional statement if-else:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
int
age =
18;
if (age > 18)
Console.WriteLine("I'm an adult");
else
Console.WriteLine("I'm still a minor");
Console.ReadLine();
}
}
}
|
In the above example, the program declares a variable of type int, which we initialize as 18. After that, we are checking if the age is greater than or equal to 18, and print a text if it returns true. If it returns false, we are executing a total different instruction, printing a different text.
Of course, what I said about the if conditional statement applies to if-else too: when having more than one instruction after the conditional check, be it if or else, place the instructions in a code block delimited by curly brackets:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
int
age =
18;
if (age > 18)
Console.WriteLine("I'm an adult");
else
{
Console.WriteLine("I'm still a minor");
Console.WriteLine("I am a teenager");
}
Console.ReadLine();
}
}
}
|
The last form of of the if statement is if-else if-else. We can use this to perform two or more conditional checks, with a default action in case none of the checks returns true. The following example illustrates this case:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
string
dayOfWeek =
"Monday";
if (dayOfWeek == "Monday")
Console.WriteLine("Today is Monday.");
else if (dayOfWeek == "Tuesday")
Console.WriteLine("Today is Tuesday.");
else if (dayOfWeek == "Wednesday")
Console.WriteLine("Today is Wednesday.");
else if (dayOfWeek == "Thursday")
Console.WriteLine("Today is Thursday.");
else if (dayOfWeek == "Friday")
{
Console.WriteLine("Today is Friday.");
Console.WriteLine("Weekend begins!");
}
else
{
Console.WriteLine("Weekend begun!");
Console.WriteLine("Today we don't go to work");
}
Console.ReadLine();
}
}
}
|
The output follows:
From the above example, you can see that we are checking our string variable against all days of the working week, writing various texts for each scenario, and a default one in case none of the checks return true.
The concepts explained in this lesson are also shown visually as part of the following video: