XML Code Comments: What, Why and How
During the years I’ve seen a lot of different ways of commenting code – some good and some bad.
My personal favourite way of commenting code is by using the XML comment feature of C# and VB.NET, but the important part of commenting code is not how you do it, but what you write in them.
Methods are the most challenging members to comment, because they perform an action and can contain many lines of code compared to e.g. properties. Because of their relative complexity they need to be well commented, so lets take a look at what that actually means.
Answer the questions
The XML comments of a method needs to answer three simple questions: What, why and how. The simplest is “what”. In a class called Dog there is a public method called Bark() and the comment that answers the “what”-question could be Makes the dog bark out loud.
Next we want to answer the “why”-question and it is a bit trickier. The answer must tell you why this method has a reason to exist. For the Bark() method it could be
Last but not least we need an answer to “how”. This one can be very hard to write and not all methods need it answered. You need to understand the “how”-question as a question about the workings of the method in non-technical terms. So the answer to the “how”-question on the Bark() method could sound something like The dog can not bark if it is eating or drinking, so if it does, it first needs to spit it out.
To make sure that all three questions get answered as often and detailed as possible and needed, we can use a simple scheme in the XML comments. Here is an example of such a scheme.
/// Makes the dog bark out loud. (what)
/// The dog has to bark every day, otherwise
/// it will get depressed and violent. (why)
/// The dog can not bark if it is eating or drinking,
/// so if it does, it first needs to spit it out. (how)
public void Bark()
if (IsEating || IsDrinking)
By using the same scheme every time you comment, it get’s easier to write and understand and the code gets well documented. It is not important what the scheme looks like as long as the three questions get answered.
Remember that you don’t need a reason to answer all three questions – you need one not to. As soon as you get that rule under your skin, it gets easier to uphold every time and before long it gets part of the daily coding routine.
Mads Kristensen currently works as a Senior Developer at Traceworks located
in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in
2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and
web services in his daily work as well. A true .NET developer with great passion for the simple solution.