Documenting Code in C#
William Olsen
Posted on April 2, 2022
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;
}
When I add the summary tag, it looks like this:
/// <summary>Doubles an integer.</summary>
public int Double(int i)
{
return i * 2;
}
For the developer interacting with Double()
, this is what is displayed:
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);
What the developer sees:
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;
}
What the developer sees:
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;
}
What the developer sees:
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!
Posted on April 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.