Alternative ways of writing if-else conditions


In C#, We can write if-else conditions with the following ways or alternative. Here we will take a example of week days. we use if-else condition to find day according to day number. After if-else condition we will see how same condition can be use with switch and unary operator in C#.

1. If-Else If-Else Statement

// Using if-else if-else 
int dayNumber = 5;
string dayType;
if (dayNumber == 1)
{
    dayType = "Monday";
}
else if (dayNumber == 2)
{
    dayType = "Tuesday";
}
else if (dayNumber == 3)
{
    dayType = "Wednesday";
}
else if (dayNumber == 4)
{
    dayType = "Thursday";
}
else if (dayNumber == 5)
{
    dayType = "Friday";
}
else if (dayNumber == 6)
{
    dayType = "Saturday";
}
else if (dayNumber == 7)
{
    dayType = "Sunday";
}
else
{
    dayType = "Invalid day";
}

2. Switch Statement

int dayNumber = 5; // You can change this value to test different cases
 // Using switch to determine the day of the week
 string day;
 switch (dayNumber)
 {
     case 1:
         day = "Monday";
         break;
     case 2:
         day = "Tuesday";
         break;
     case 3:
         day = "Wednesday";
         break;
     case 4:
         day = "Thursday";
         break;
     case 5:
         day = "Friday";
         break;
     case 6:
         day = "Saturday";
         break;
     case 7:
         day = "Sunday";
         break;
     default:
         day = "Invalid day";
         break;
 }

3. Ternary Operator

// Using Ternary operator 
 int dayNumber = 5;
string mm = dayNumber == 1 ? "Monday" : dayNumber == 2? "Tuesday" : dayNumber == 3? "Wednesday" : dayNumber == 4? "Thursday" : dayNumber == 5? "Friday" : dayNumber == 6?"Saturday": dayNumber == 7? "Sunday" : "Invalid day";

Next