DEV Community

William Olsen
William Olsen

Posted on

Documenting Code in C#

Oh boy, it's that time again. Ever get that feeling of dread when you write a new feature, realizing that you need to document the code for it?

We've all been there. But hopefully, this guide can help alleviate the pain of trying to standardize documentation across your codebase.

First, we need to establish how C# Intellisense handles suggestion comments. The format is akin to XML in commented-out code. There are many special tags to help document your method/class/field, but only a few really matter.

The most important tag in my opinion is the <summary> tag. This tag allows you to make a summary of what your code does. For an example, let's make a simple method.

This method takes an integer as a parameter and returns the value doubled:

public int Double(int i)
{
    return i * 2;
}
Enter fullscreen mode Exit fullscreen mode

When I add the summary tag, it looks like this:

/// <summary>Doubles an integer.</summary>
public int Double(int i)
{
    return i * 2;
}
Enter fullscreen mode Exit fullscreen mode

For the developer interacting with Double(), this is what is displayed:

The result.

The second most important tag is the <value> tag. Now this tag only really applies to fields, and is basically a summary for variables.

An example:

/// <value>The value of 2 doubled.</value>
public int DoubledNumber = Double(2);
Enter fullscreen mode Exit fullscreen mode

What the developer sees:

The result.

The second-to-last tag I deem necessary is the <returns> tag. The use of this tag is kind of in-the-name (it informs about what the method returns).

Going back to Double(), here's an example:

/// <summary>Doubles an integer.</summary>
/// <returns>An integer.</returns>
public int Double(int i)
{
    return i * 2;
}
Enter fullscreen mode Exit fullscreen mode

What the developer sees:

The result.

Notice how the information is starting to pile up. This is one of the reasons I prefer to only have a few tags per method - we don't want to overwhelm the developer with trivial information.

The last tag we will discuss is the <param> tag. This is used in a slightly different way than the other ones, so pay attention. Essentially, the tag is used to give information about each individual parameter in a method.

An example:

/// <summary>Doubles an integer.</summary>
/// <returns>An integer.</returns>
/// <param name="i">The integer to double.</param>
public int Double(int i)
{
    return i * 2;
}
Enter fullscreen mode Exit fullscreen mode

What the developer sees:

The result.

Even though I only used the <param> tag once, you can stack it for as many paramaters as you want.

Now that we went over the basic tags, you should have a general understanding of how the comment system works. If you want to learn about more tags, I find this Microsoft reference article works fine.

Thanks for reading!

Discussion (0)