Clean Code in C#: Principles and Examples for .NET Developers

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Clean Code in C#: Principles and Practical Examples



Clean Code is not just a trendy term, but a fundamental skill for a professional developer. In the .NET and C# ecosystem, where projects often live for years and are maintained by dozens of programmers, the ability to write understandable and easily modifiable code becomes critically important. In this article, we will break down the main principles of Clean Code as applied to C# and look at specific examples of their use.



Why is Clean Code Important in C#?

C# is a strongly typed, object-oriented language with a rich ecosystem. However, its power can turn into chaos if discipline is not followed. Clean code reduces the number of bugs, accelerates the onboarding of new developers, and lowers maintenance costs. As Robert Martin said: "The only way to go fast is to go well."



Principle 1: Meaningful Names

Names of variables, methods, and classes should reveal intent. Don't skimp on characters — bad code takes more time to understand.



Bad Example

int d; // time since modificationList<int> lst = new List<int>();void Proc(int a, int b) { ... }


Good Example (Clean Code)

int elapsedTimeInDays;List<int> customerIds = new List<int>();void CalculateDiscount(decimal basePrice, decimal taxRate) { ... }


Rule: If a name requires a comment, it is a bad name. Use camelCase for variables and PascalCase for methods and classes.



Principle 2: Small Functions (SRP at the Method Level)

Each function should do exactly one thing and do it well. If a method contains more than 20-30 lines or has more than two levels of nesting, it is a signal for refactoring.



Bad Example: Swiss Army Knife Function

public void ProcessOrder(Order order){    // Validation    if (order == null || order.Items.Count == 0)        throw new ArgumentException("Invalid order");

// Discount calculation decimal discount = 0; if (order.Total > 1000) discount = 0.1m; else if (order.Total > 500) discount = 0.05m;

// Save to DB using var db = new AppDbContext(); db.Orders.Add(order); db.SaveChanges();

// Send email SendEmail(order.CustomerEmail, "Order received");}


Good Example: Separation of Concerns

public void ProcessOrder(Order order){    Validate(order);    var discount = CalculateDiscount(order.Total);    ApplyDiscount(order, discount);    SaveOrder(order);    SendConfirmationEmail(order);}

private void Validate(Order order){ if (order == null || order.Items.Count == 0) throw new ArgumentException("Invalid order");}

private decimal CalculateDiscount(decimal total){ if (total > 1000) return 0.1m; if (total > 500) return 0.05m; return 0;}

private void SaveOrder(Order order){ using var db = new AppDbContext(); db.Orders.Add(order); db.SaveChanges();}


Principle 3: Avoid Duplication (DRY)

Repetitive code is the root of all evil. If you copy a block of code more than once, extract it into a method or class.



Example: Duplicated Logic

// In user controllerif (user.Role == "Admin" || user.Role == "Manager")    GrantAccess();

// In report controllerif (user.Role == "Admin" || user.Role == "Manager") ShowReport();


Refactoring: Encapsulating the Check

public static class UserExtensions{    public static bool HasElevatedPermissions(this User user)    {        return user.Role == "Admin" || user.Role == "Manager";    }}

// Usageif (user.HasElevatedPermissions()) GrantAccess();


Principle 4: Comments are Evil (Except for

Blogs

Book Recommendations