Member-only story
C# tip— change switch statements to switch expressions
2 min readFeb 29, 2020
I am not a big fan of the switch statement.
For all the classic reasons:
- it is difficult to maintain
- it provides an opportunity for redundant code
- switching on type is usually a code smell
- it is so long
For this last reason, have a look at a simple switch statement that determines the week day name starting from the weekday number:
int dayNumber = 1;
String dayName = “”;
switch (dayNumber)
{
case 1:
dayName = “monday”;
break; case 2:
dayName = “tuesday”;
break; case 3:
dayName = “wednesday”;
break; case 4:
dayName = “thursday”;
break; case 5:
dayName = “friday”;
break; case 6:
dayName = “saturday”;
break; case 7:
dayName = “sunday”;
break; default:
break;
}
26 lines of code for such a simple thing!
How can you like something like this?
Is there a simpler and shorter way?