Comments in C#: Use Them Well or Not at All

Developer FabioDeveloper Fabio
2 min read

Comments are a controversial topic in clean coding. On one hand, they can help clarify code; on the other, they can be a symptom of poor quality or a maintenance burden.

In this article, we'll explore when comments are helpful, when they are a code smell, and how to manage them effectively in C#.


Comments Should Explain the "Why," Not the "What"

If a comment describes exactly what the code is doing, it’s often redundant or even harmful.

❌ Bad comment:

// Increments the counter by 1
counter++;

✅ Better: write a clear name instead:

counter.Increment();

Use Clear, Self-Explanatory Names

The first step to reducing the need for comments is to use variable, method, and class names that speak for themselves.

// ❌
int d; // day

// ✅
int dayOfMonth;

When Comments Are Useful

  • To explain the reason behind a non-obvious or complex choice

  • To warn about limitations or temporary workarounds

  • To document contracts, preconditions, and postconditions

  • To mark TODOs or FIXMEs using dedicated tools

Example:

// We use this raw query because EF doesn’t yet support the XYZ function
var results = context.Database.ExecuteSqlRaw("...");

Avoid Comments That Describe Obvious or Redundant Code

Worse than no comment is an outdated or incorrect one.


XML Documentation Comments

In C#, use XML comments (///) to describe the public API of classes and methods. This allows for automatic documentation generation.

/// <summary>
/// Calculates the total number of items in the order.
/// </summary>
/// <param name="order">The order to calculate.</param>
/// <returns>Total as a decimal.</returns>
public decimal CalculateTotal(Order order) { ... }

Tools and Practices for Comments

  • Use static analyzers to detect outdated or duplicate comments

  • Keep comments up to date as part of code reviews

  • Use documentation tools (e.g., DocFX, Sandcastle) to generate API docs


Final Thought

The best comment is clear code.
When code becomes too complex to explain with a comment, it might be time to refactor.


Conclusion

Comments are a valuable tool, but they should be used wisely.
Always aim to write code that speaks for itself, and use comments to enhance—never replace—clarity.

In the next article, we’ll discuss Dependency Injection in C# and how to use it to keep your code modular and testable.

0
Subscribe to my newsletter

Read articles from Developer Fabio directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Developer Fabio
Developer Fabio

I'm a fullstack developer and my stack is includes .net, angular, reactjs, mondodb and mssql I currently work in a little tourism company, I'm not only a developer but I manage a team and customers. I love learning new things and I like the continuous comparison with other people on ideas.