Every developer encounters a situation where they have to write a logic that requires checking multiple conditions but out of them only one can be true.
Let's take an example- We have to figure out the type of car based on the dimensions given. We have a class Car.cs having properties like length and width.
public class Car {
public decimal Length { get; set; }
public decimal Width { get; set; }
// other properties
}
There are various ways to deal with this:
Using If..Else
This is the most conventional no brainer way is using if..else
public string GetCarType(Car car)
{
var carType = "";
if (car.Length <= 4.1 && car.Width <= 1.7) {
carType = "Hatchback";
} else if (car.Length <= 5.6 && car.Width <= 2) {
carType = "Sedan";
} else (car.Length > 5.6 && car.Width > 2) {
carType = "Pickup Truck";
}
return carType;
}
Using multiple If
Using multiple if instead of if-else can be used to make the above code look cleaner.
public string GetCarType(Car car)
{
if (car.Length <= 4.1 && car.Width <= 1.7) {
return "Hatchback";
}
if (car.Length <= 5.6 && car.Width <= 2) {
return "Sedan";
}
if (car.Length > 5.6 && car.Width > 2) {
return "Pickup Truck";
}
return "";
}
Using switch case
Thanks to C# 7.0, now we can add boolean conditions in our switch cases and say goodbye to if-else forever (not literally ๐). Let's transform the above code using a switch statement.
public string GetCarType(Car car)
{
var carType = "";
switch (car)
{
case var dimensions when dimensions.Length <= 4.1 && dimensions.Width <= 1.7:
carType = "Hatchback";
break;
case var dimensions when dimensions.Length <= 5.6 && dimensions.Width <= 2:
carType = "Sedan";
break;
default: carType = "Pickup Truck";
break;
}
return carType;
}
Hope this not-so-new but hidden feature of C# will help you write more presentable code in the future.
Also, buy me a coffee, book or a pizza by clicking the image above if you like what I am doing and want to support me. ๐
Do you know any other way we can replace multiple if..else? Lemme know in the comments below.