ExtractXml: Including Examples in Your API Documentation

When using an API it's always nice to have some examples showing how the different classes and their methods and properties are actually used. Examples usually come in two flavors:

  • Full projects (more or less) ready to compile
  • Code snippets in the documentation (e.g. generated by NDoc)

Ok, I have to admit that I tend to ignore the full projects. When I need an example to understand something, I'm often looking for quick answers - not easy to get in an example project sometimes showing several concepts at once.

The small examples usually consist of maybe only a few lines of code, that in many cases are not ready to be compiled (at least not without adding some more code). But often these examples are exactly what is required to get quick help, getting straight to the point.

Unfortunately for the API developer, sample code inside the <example> tag of the XML Doc comments is a pain to create and maintain.

  • The code has to be tested.
    A missing semicolon in an example is definitely not the best way to convince the API users of the quality of the documentation. And if the code shows something that simply is not possible (e.g. a feature that was planned, but later cut from the release), people get really upset.
  • The code has to reflect the current state of the API.
    As the work on the API continues, sample code copied and pasted into your documentation has to be updated over and over again.

With a large number of examples, the only real solution is to take sample code from actually working code (e.g. from some of the NUnit tests for the API) and to automatically insert these code snippets into the doc comments.

The <include> tag of the XML doc comments allows the inclusion of XML fragments stored in an external XML file. I wrote a small command line tool (ExtractXml) that generates an XML file from a ".cs" file. Read more about it here.

No Comments