5 Bad Practices to Avoid in C#

Christ khodabakhshi
2 min readDec 10, 2022

In this post, I want to give 5 little examples of bad practices in C# and what can be done instead to improve your code a little bit. If you are an intermediate C# developer, you should know these already, and if not you will learn them today.

Use Ternary Operator Instead of If Else

In most cases, it’s cleaner to use a Ternary Operator instead of an If Else condition because it will take less space and will make your code more readable.

if (age >= 18) { 
return "You are an adult";
}
else {
return "You are not an adult";
}

We can fit these 6 lines in one line like this:

return age >= 18 ? "You are an adult" : "You are not an adult";

Use Enum Instead of Hard-Coded Numbers

Whenever you can use an enum instead of a random number in your code, it will increase the readability of your code and reduce the possibility of making mistakes.

Don’t do this:

if(month == 2) { 
days = 28;
}

Instead, do this:

enum Months { 
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11…

--

--

Christ khodabakhshi

Software developer, dad, coffee fan, and keen on talking about business ideas and investments.