Decision statements are used to control the flow of execution of the code. These statements are used to execute particular piece of code if or if not a certain condition is met. There are four major types of decision statements in C#.
If statements are used when you want to execute or exclude piece of code if a certain condition is met or not. Have a look at this example.
using System;
namespace CSharpTutorials {
class Tutorial {
static void Main(string[] args) {
string sky = "blue";
if (sky == "blue") {
Console.WriteLine("It is day time.");
}
Console.ReadKey();
}
}
}
In the last example, what if we want something else be printed if sky variable contains value other than “blue”? In such cases if/else statements are used. Have a look at this example.
using System;
namespace CSharpTutorials {
class Tutorial {
static void Main(string[] args) {
string sky = "grey";
if (sky == "blue") {
Console.WriteLine("It is day time.");
}
else {
Console.WriteLine("The sky is not clear.");
}
Console.ReadKey();
}
}
}
In the above code if “sky” variable contains value other than “blue”, the console screen shall print that “The sky is not clear.”
A sky can have multiple colors, what if we want to print different statement depending upon the color of the sky? Such a scenario can be handled by using else if statements. Consider the next example.
using System;
namespace CSharpTutorials {
class Tutorial {
static void Main(string[] args) {
string sky = "grey";
if (sky == "blue") {
Console.WriteLine("Weather is clear");
}
else if (sky == "grey") {
Console.WriteLine("Weather is cloudy");
}
else if (sky == "black") {
Console.WriteLine("It is night");
}
else {
Console.WriteLine("No information about weather.");
}
Console.ReadKey();
}
}
}
In the above code, the sky variable is initialized to “grey”. If and else if statements are being used in conjunction in order to handle blue, grey, black and other values of the sky.
If large number of “if” and else if statements are required to implement a logic, it is more convenient to use switch statements. In switch statement the value to be compared is passed as a parameter to switch statement. This value is then compared with each case statement and the case statement whose value matches with this passed value, is executed. Let us see how the sky color example can be implemented via switch statement.
using System;
namespace CSharpTutorials {
class Tutorial {
static void Main(string[] args) {
string sky = "grey";
switch (sky) {
case "blue": {
Console.WriteLine("Weather is clear");
break;
}
case "grey": {
Console.WriteLine("Weather is cloudy");
break;
}
case "black": {
Console.WriteLine("It is night");
break;
}
default: {
Console.WriteLine("No information about weather.");
break;
}
}
Console.ReadKey();
}
}
}