C# - Decision Making


What is Decision Making?

Sometime in program we need to test one or more conditions to execute the specific block of code. These constructs are required in controlling the flow of your program based on specific conditions. in C#, you can perform decision-making by using various control structures like if, else if, else, switch, and ternary operator (? :)

if Statement

The if statement executes a block of code if a specified condition is true. We can specify more than one condition in single if statement.

int number = 10; 
if (number > 0) 
{ 
    Console.WriteLine("Number is positive."); 
} 
else 
{ 
    Console.WriteLine("Number is zero or negative."); 
}

else if Statement

An if statement can be followed by an optional else statement, else if statement executes when if statement return false.

int number = 10; 
if (number > 0) 
{ 
    Console.WriteLine("Number is positive."); 
} 
else if (number < 0) 
{ 
    Console.WriteLine("Number is negative."); 
} 
else 
{
    Console.WriteLine("Number is zero."); 
}

Switch Statement

The switch statement is used to select one of many code blocks to be executed. Switch statement evaluates an expression and compares it with a series of cases.

int day = 3;
string dayString; 

switch (day) 
{ 
    case 1: 
        dayString = "Monday"; 
        break; 
    case 2: 
        dayString = "Tuesday"; 
        break; 
    case 3: 
        dayString = "Wednesday"; 
        break; 
    default: 
        dayString = "Other day"; 
        break; 
}

Console.WriteLine($"Day is {dayString}");

Ternary Operator

It is a short way to write a if-else statement.

int number = 10; 
string result = (number > 0) ? "Positive" : "Non-positive"; Console.WriteLine(result);