Member-only story

10 Must-Know C# Code Smells and How to Fix Them

Detect and Fix C# Code Flaws

Alex Maher
4 min readAug 28, 2024

Introduction

Writing C# code that is clean and easy to maintain is a skill that takes time to develop. One common hurdle developers face is dealing with “code smells.” These are signs that something might be wrong in the code. Here are 10 must-know C# code smells and how to fix them.

1. Long Methods

Problem: Methods that are too long are hard to understand and maintain. They often do too many things at once. Solution: Break the method into smaller, more focused methods. This is also known as the Single Responsibility Principle (SRP).

Example:

public void ProcessOrder(Order order)
{
ValidateOrder(order);
CalculateShipping(order);
SaveToDatabase(order);
}

2. Duplicate Code

Problem: Copy-pasting code is a common mistake. It can lead to bugs and makes updates harder. Solution: Use functions or methods to encapsulate the duplicated code.

Example:

public void PrintCustomerDetails(Customer customer)
{
Console.WriteLine($"Name: {customer.Name}, Age: {customer.Age}");
}

public void PrintOrderDetails(Order order)
{

--

--

Alex Maher
Alex Maher

Written by Alex Maher

.NET C# dev with 10+ yrs exp, self-taught & passionate web developer. Sharing tips & experiences in C# and web dev.

Responses (7)