My Comments on Comments

Created: January 3, 2015 Tagged As: .net, C#, General, Language Share:

Over the years I have "inherited" code from my clients that borders on horrible. It is usually a mess of spaghetti that was cobbled together by a non-programmer over several years. My unfortunate task is to make sense out of it in an effort to provide a cost for a complete rewrite.

One of the worst problems I encounter is a complete lack of code commenting. This leaves me wondering why things work the way they do - is that a bug or correct behavior?

Code commenting can alleviate many questions. It is also invaluable when working on a team to keep everyone on the same page.

I know you're probably thinking that the code repository will handle all of this for you with its line-by-line change tracking, revision history browser, fancy reporting, etc. That is true. But pulling history from the repository takes time. And what if the repository crashes and you are left with only the current copy?

Inline commenting in your code is the only surefire way to clearly and quickly convey your thoughts. Microsoft knows this and provides three really good mechanisms in all of its .net languages.

Triple-Slash Comments

My first go-to option is always the triple-slash comments at the top of classes, properties, and methods. All you need to do is, after declaring a class, or writing a property or method, go to the top of it and type ///. Visual Studio will perform some magic and you can then describe the object, all of the parameters, and the return value.

The coolest things about this is that this information feeds Intellisense so that whenever you go to use this code, Visual Studio will show your notations as you type!

Inline Comments

Now that you've briefly described what your class, property or method does, the next step is inline commenting. This is the process of using // (or ' in VB.net) to put a comment inline with your code to tell your future self or other coders what certain, possibly confusing, parts of your code are doing.

It all makes so much sense when you're writing the code, but try to imagine yourself looking at it in a year and trying to understand what is going on. If anything looks questionable, comment it!

XML Comment Generation

If you are producing a library that will be redistributed for people outside of your team to use, then you will want to use the XML comment generator option in Visual Studio. If you currently use any third-party toolkits you've probably noticed most of them ship with an XML file that has the same name as the DLL. This is the output of the XML comment generation tool.

To enable this feature, right-click on your project and select Properties. Click on the "Build" tab.

Now each time you build your project an XML file will be generated that contains the contents of all of your /// comments. And when this is distributed with your DLL, other developers will see them in Intellisense.