Say Goodbye to multiple If Else

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.

Do you know any other way we can replace multiple if..else? Lemme know in the comments below. Also, check out my other blog where I talk about the most commonly used string methods in C#.

Buy me a coffee, book, or cheeseburger by clicking this image if you like my work and want to support me.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top