How to Document Your .NET Code with XML Comments

Microsoft .NET

In any professional environment, properly documenting your code with comments is necessary for long-term readability. For .NET code, Microsoft provides a system for XML-based comments that provide enhanced IDE support.

What Are XML Comments?

Essentially, XML comments are a special kind of comment denoted with a triple slash (///) and XML tags to give the comment some structure. For example, a simple summary comment would look like the following:

 Simple summary comment in .NET code.

The point of this is that when you go to use this method elsewhere in your code, Visual Studio can look at the XML, and add some information directly in the Intellisense pop-up. This system works for all kinds of types, and can even be used to document return values and individual parameters. And, when you distribute the assembly, you can distribute the XML file with it to enable these same features for anyone using your class library. This also enables easy use of static documentation generators like DocFX and Sandcastle.

Surprisingly, this feature is mostly just a .NET thing. Nothing prevents you from using the practice with other languages, but it’s something that Microsoft supports well for their languages and editors, and other languages usually don’t have proper support for it. We’d love to see support for this expanded to other languages and editors, as it’s pretty universally useful.

It’s very simple to use. Simple hit the slash key three times (///) above a method, class, or other type, and Visual Studio will insert a template for you to type in. This saves you the hassle of typing it out manually, which means there’s really no reason to not use these over traditional double slash comments.

Hit slash key three times (///) above a method, class, or other type, and Visual Studio will insert a template to type in.

If your method has a return type or parameters, Visual Studio will generate fields for those as well. You’ll see your comments when you go to use the method:

Visual Studio will generate fields for return types or parameters as well.

The standard supports many kinds of tags:

  • <summary> shows in Intellisense whenever you use the method.
  • <remarks> is like summary, but doesn’t show in Intellisense (useful for writing extended documentation).
  • <returns> documents the return type.
  • <exception> lets developers know what exceptions the method can throw.
  • <value> is like returns but for class properties.
  • <example> shows a code example for the documentation (use this with <code>).
  •  <see> and <seealso> generate clickables links to other methods, usually used for documenting overloads.
  • <list> allows using lists to order elements.

You can read Microsoft’s documentation on the XML comment standard for more information.

Source

Author: admin

Leave a Reply

Your email address will not be published. Required fields are marked *