If you’re a regular reader of this blog, you’ll know that code documentation is a topic we tend to cover with a certain frequency. Another common topic is concepts related to the C# language. In today’s post, we make these two common subjects converge, by presenting a guide on C# documentation.
We’ll show you a step-by-step guide that will walk you through the necessary steps you need to take to create documentation for your C# code. You’ll start by adding documentation to your code using special XML comments and end by seeing how to generate rich documentation created from these comments. You’ll learn about the importance of code documentation, see how Visual Studio can turn the documentation you create into useful help messages, and get to know some tools that can help you in this work. Let’s get started!
Code Documentation: Why Bother?
We begin by explaining the motivations behind code documentation in C# or any other programming language. “Why should I bother with software documentation,” you might be wondering, “when I already have so much to do?” And that’d be a fair question.
If you think software documentation is useless, then you wouldn’t be lacking for company, since many developers appear to think the same. Such developers will say that writing documentation for your source code is, at best, poor use of your time. That instead of “wasting” time documenting code, you should strive to make it self-explanatory, so that documentation isn’t even needed in the first place.
Make no mistake here: writing clean, self-documenting code is a good, useful goal to strive for. Unfortunately, it’s easier said than done and often, despite our best efforts, self-explanatory code just doesn’t explain itself enough. You might have to deal with an unusual domain, with concepts that most people don’t come across in their day-to-day lives. Perhaps, the concepts you have to model through code are just intrinsically complex and there’s no way to simplify them further (google “essential vs accidental complexity” to learn more about this.) Code documentation goes where self-documenting code can’t.
Another point in favor of code documentation: sometimes, documentation is all a consumer has. When you’re dealing with a tool (library, framework, etc) published by a third-party, documentation is more often than not the only clue you have into the mind of its authors. Without some form of written guide on what that code does, you’d be totally lost. So, if you create code that’s going to be consumed by people outside your organization, you have even more reasons to document it.
C# Documentation: A Step-By-Step Guide
We’ll now walk you through the steps needed to create and consume documentation for your C# code, from beginning to end.
XML Documentation Tags
We’ll start by covering one of the most basic?and yet powerful?ways you can add documentation to your C# class: XML documentation tags. What are those?
XML documentation tags are a special kind of comment in C#. You can add them above a class definition, or above methods, operators, indexers, constructors, and properties. The tags allow you to add valuable information about the member you’re describing. The exact tags you’ll be using depends on both the type of member you’re documenting and on some characteristics of said member. Things will be clearer with an example.
Creating an Example
Let’s say we’re writing an application to manage a library and now our task is to create the BookRepository class. We could have a method that searches and retrieves a book by its ISBN:
public Book FindByIsbn(string isbn) { if (isbn == null) throw new ArgumentNullException(); if (isbn.Trim() == string.Empty) throw new ArgumentException(message: "ISBN must be a valid, non-empty string!"); // the rest of the code is ommited due to brevity }
For brevity’s sake, I’ve omitted the useful part of the method, but it doesn’t matter for our purposes here. When thinking about the documentation of members, we’re only interested in the public interface, not the internal implementation. You might also object to my usage of a humble string to represent the ISBN, and I’d agree with you. On a real application, I’d represent this domain concept with a dedicated value object?not to be mistaken with value types, i.e. structs. For simplicity, it will remain as a string. Let’s move on.
Adding a Documentation Stub and Adding Information to It
We’re now going to create code documentation for the method above, using XML documentation tags. To do that, we can place the cursor above the method and press the forward-slash key 3 times in a row. After doing that, the following documentation stub will appear above the method:
/// <summary> /// /// </summary> /// <param name="isbn"></param> /// <returns></returns>
As you can see, Visual Studio automatically adds some tags for us. These are far from being the complete list of tags, but are the most common ones. We’re going to briefly explain them, one by one while providing the content for them at the same time.
The <summary> Tag
We start with “summary” tag. This tag allows you to describe what the method (or property, indexer, etc) does. The text you write here should be as informative and concise as possible, and it’s a convention to write the description in the simple present tense. For this particular method, I’d use a summary like this: “Searches and returns the book identified by the specified ISBN.”
The <param> Tag
Next, we have the “param” tag. Besides the content?the description?the tag also features an attribute, “name”. This is the text I’d provide for this “param” tag:
The System.String instance that represents the ISBN of the book to search for.
The <returns> Tag
Finally, we have the “returns” tag which, unsurprisingly, allows you to describe the return value of the method. The convention here is to also use the simple present tense. It’s recommended to describe not only the happy path but also unexpected scenarios. For instance, what happens when the method can’t find a book with the specified ISBN? Let’s pretend the method is properly implemented and it returns null when no book can be found. You have to include this information within the “returns” tag. This is how I’d do it:
An instance of Book representing the element with the specified ISBN, if found; otherwise, null.
Wrapping-Up the Example With Exception
We’re done with the default tags VS adds for us, but there’s another very useful tag we could add: the “exception” tag. As its name implies, this tag is used to describe the exception(s) the method can throw, so consumers can decide how (or whether) to handle them. For brevity’s sake, we’ll omit the explanation about the exception tag and skip right into the finished example:
/// <summary> /// Searches and returns the book identified by the specified ISBN. /// </summary> /// <param name="isbn">The <see cref="System.String"/> instance that represents the ISBN of the book to search for.</param> /// <returns>An instance of the <see cref="Book"/> class representing the element with the specified ISBN, if found; otherwise, <c>null</c>.</returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="isbn"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="isbn"/> is an empty or white-space string. /// </exception>
As you can see, the final example features some additional tags, such as <paramref> and <see>. We won’t go into detail into them since we already have posts going in-depth into XML documentation tags. Suffice to say that these tags allow you to reference existing artifacts (classes, parameters) in the application, and their content is validated by the compiler.
You might now be wondering what’s the point of all that. Sure, we use these tags to add some descriptions about our members, and so what? How is the information expressed by the tags going to be used? What’s the next step?
Intellisense
The content you express using XML documentation tags is used in several ways to display useful information about your artifacts. One of the most useful of such mechanisms is the Intellisense feature in Visual Studio.
Intellisense turns your XML comments into help messages that show up when you’re using VS. I’m going to use the method from the previous example to show how this works. Let’s say we need to use the “FindByIsbn” method from our BookRepository class and we write the following lines:
static void Main(string[] args) { var repo = new BookRepository(); var result = repo.FindByIsbn("0486415872"); }
When selecting the method from the Intellisense list, you can already see the summary you’ve written:
After selecting the method and typing the open parenthesis, you’ll see another help message, this time displaying the text from the <param> tag besides the text from <summary>:
When you hover the cursor over the method’s name, you’ll see, besides the description from <summary>, the list of exceptions that the method can throw:
These examples clearly demonstrate the importance of writing informative description since often they are the only source of information a consumer of the API can rely on.
Intellisense is a very useful feature that rely on XML documentation tags, but it’s not the only one.
Documentation Generation
You could think of the help messages Intellisense shows you as dynamic documentation. It’s documentation that shows up to you, in response to interactions you have with your code. What about more static forms of documentation? Could we also get those from documentation tags as well? Yes, we can.
On the solution explorer window, right-click the relevant project, click on properties. When a new window shows up, go to the “Build” tab. On the bottom of the windows you’ll see this:
You can then check the “XML documentation file” box and enter a path for an XML file. After doing that, every time you build the application, an XML output file will be generated, containing the documentation comments for the project. This is equivalent to using the “-doc:file” option when compiling by command line.
You can then take this one step further and employ tools that take this XML file and use it to generate richer documentation (for example, pdfs or HTML files.)
Tools at Your Disposal
After you’ve written a lot of documentation in the form of XML tags, you’ll notice that many such comments tend to be a bit repetitive. You’ll no doubt reach the conclusion that at least a portion of them could be automatically generated.
The first tool I want to mention is Pandoc. It can convert to and from many document formats.
That can really help your documentation efforts. Let’s say you have documentation written in markdown, versioned along with your source code. During build, you could use Pandoc to convert the markdown files to, let’s say, HTML, and upload them to your server. Neat!
The second tool on our small list here is StyleCop. This tool is an automatic enforcer for your code standards. You might wonder what this has to do with documenting, and the answer is a lot. For starters, one of the rules that StyleCop validates is the presence of XML documentation comments for every public member of your application. And since StyleCop helps your team write code using a homogeneous style across the board, it helps you on the “self-documenting code” front as well.
The last tool we’re going to mention here does exactly that. We’re talking about GhostDoc, which is a tool offered by SubMain.
GhostDoc is able to generate the XML documentation tags for you, based on the existing code for your methods, indexers, classes and other artifacts. It also checks the spelling of your C# code, which matters more than you might think. You’ll then get the chance to review the generated documentation and change it as needed. Sure, you won’t be able to use the generated documentation 100% as-is, but the tool will eliminate a lot of repetitive work from your pipeline. The enterprise edition of GhostDoc can also take the resulting XML output and turn it into help files, which you can then easily upload to a server and make it available to your organization.
C# Documentation: Believe It or Not, You Need It
This post was a simple yet complete guide on C# documentation. We’ve shown the list of steps you must take if you’re to reap the benefits of code documentation. But of course, there’s a lot more to it than we could hope to cover with a single blog post. If you want to learn more, not only about documentation but also about C# concepts or best practices, the SubMain blog is the right place for you. Keep coming back to see more content that will help you with your career as a developer.
Thanks for reading!
Learn how GhostDoc can help to simplify your XML Comments, produce and maintain quality help documentation.
1 Comment. Leave new
Where we can find a full reference of C# classes and methods ?.
Most of the books contains samples for teaching the language, but I need a dictionary guide that listing all commands.
Where to find it ?.