When you write code in .NET, you often use XML comments to document your code. XML comments are a great way to keep your code organized and easy to read. XML comments can be used in any place where you want to document your code, including the source code, the project’s documentation, or even a white paper. Here’s how to use XML comments in .NET:
- Start by creating a new file called “comments.xml” in the root of your project. This file will contain all of the comments for your code.
- In the Comments field of the file, enter some basic information about your code. For example, you might say that this is a function call:
Function call - Next, add some more information about your function call. You might say that this function takes an argument:
- Finally, add some notes about how your function works:
This is a comment on how my function works.
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:
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.
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:
The standard supports many kinds of tags:
).
and generate clickables links to other methods, usually used for documenting overloads.
allows using lists to order elements.You can read Microsoft’s documentation on the XML comment standard for more information.
Related Video