Reusable XML Documentation Comments
When working on C# projects, we often use XML documentation comments to describe types and members. Besides improving maintainability, these comments can also be turned into API documentation automatically by tooling.
But comments need maintaining too. Overloaded methods run into a recurring problem: a group of overloads usually share very similar comments, and editing them one by one makes it easy to end up with lots of subtle inconsistencies between overloads. It also makes maintaining the comments more tedious and fiddly.
The official XML documentation comments documentation is thorough, so this article won’t cover those details. Instead it focuses on ways to reuse comments.
<inheritdoc>
First is the <inheritdoc> tag, which is one of the more commonly used options. Here is an example:
1 | public class FluentUriBuilder |
You can see that the parameterless Create() method has a comment line Create <see cref="FluentUriBuilder"/>.. The other overload should use the same comment as its base and may want to add a description specific to that overload. This is exactly where <inheritdoc cref="Create()"/> comes in: it “inherits” the comment from the parameterless method and lets you append extra notes.
This approach has some drawbacks, though. First, once you have many overloads the comments fill up with inheritance statements, which hurts readability. Second, deciding which overload’s comment should serve as the base can easily become inconsistent. Both drawbacks meaningfully reduce the maintainability of the comments.
Overall: usable, but the maintainability is on the weaker side.
<include>
The same code snippet becomes the following:
1 | public class FluentUriBuilder |
This approach pulls the shared comments out into a separate XML file stored under Properties, like so:
1 | <SharedComments> |
The advantage is that it avoids the confusion caused by <inheritdoc> “inheriting” comments back and forth between methods. The trade-off is that it requires an extra comments file, and in terms of readability it’s about on par with <inheritdoc>.
Conclusion
XML documentation comments are simple, but they actually come with a whole variety of tags that let us maintain the API comments as a natural part of maintaining the code. This can be a huge help for automatically generated API docs, minimizing the extra cost and risk of maintaining documentation separately. Because comments aren’t protected by the compiler, it’s hard to notice when they break; making good use of XML documentation comments makes it easier to keep comments high quality.