07 September 2007

Documenting Code in Visual Studio.Net - Part I

After writing that incredible .Net program comes the questions about support and documentation. Some people like Visio and other pictorial views of the documentation. I like external tools too...but I have always been an advocate of keeping the code and documentation together. What if the code changes? How do you update the documentation and keep everything current?

And then there is a question of style and standards. How do you enforce documentation standards for multiple developers...assuming you can get them to document in the first place. And what about the clutter that happens when people start writing all the comments within the code?

Automated Documentation in VS.Net
Luckily, Visual Studio.Net creates a standard method for documenting code. It creates a standard that is easy to stick to and I believe it even promotes more documentation*. The way to document code is to go to a class or method definition and type /// immediately above the definition of choice. VS.Net will then automatically add some commented XML to the file in question. If you are writing comments for a method with arguments, VS.Net will also creates for the arguments. If the method returns a value, an XML tag will be created for the XML value.

For example, let's say you have the following method:

public DataTable SelectInner(string TableName, string RelationName) {...}

Typing 3 slashes above the call, will automatically produce the following XML:

/// <summary>
///
/// </summary>
/// <param name="TableName"></param>
/// <param name="RelationName"></param>
/// <returns></returns>

To document the method, simply type your comments within the tags. The 'summary' tag defines the method, the 'param' tags define each parameter, and the 'returns' tag defines the return value. It's simple and give the user a quick place to define all the key inputs and outputs of the method.

Documenting code that is internal to the method is similar, but more free form. Simply type /// above the line or variable in question. VS.Net does not create fields, but these comments become more important in the next step, which is generating human readable documentation from the source files.

MSDN has documented their recognized tags. For further reading, check out this article, entitled 'XML Comments Let You Build Documentation Directly From Your Visual Studio .NET Source Files'.

-------------
* This posting applies to Visual C#/Visual C++ only. While there is theoretical support for J# and VB.Net, I have not personally tested it and therefore cannot vouch for how well it works.