What’s up with /doc?

Using the XML Documentation Features of C#

Sharp Shooter


TECHNOLOGIES: Documentation | XML | Help Files


What's up with /doc?

Using the XML Documentation Features of C#


By Mike Amundsen


It's great that Microsoft has created a platform on which all languages can participate equally. It's also great that the language teams still find ways to make their compilers unique without making them incompatible. The C# compiler has a handful of tricks up its digital sleeve, and one I particularly like is the ability to support in-line commenting for use in generating validated help-file documentation.


In this column, you'll get a look at the /doc switch on the compiler. You'll also see how you can use it to turn code comments into detailed help files with the aid of some eXtensible Stylesheet Language (XSL) and Cascading Style Sheet (CSS), and even an open-source program named NDoc. Along the way, you'll learn how you can use the C# compiler to validate your comments against the actual code. You even can use external XML files as the source for your validated documentation files. Finally, I'll show you how Visual Studio .NET automatically uses the doc files to support extended help and object documentation in the editor shell.


The Basics of /doc Commenting

The process of adding validated comments to your code is fairly simple. The C# compiler supports a collection of pre-defined XML elements you can add to your source code. Then, the compiler uses these pre-defined XML elements to generate a final XML file that is stored on disk. This XML file can be used with Visual Studio .NET to provide added online documentation of your components. You also can use this file with third-party documentation-generating tools to create online and print versions of your component documentation. Finally, you can use the same XML file along with standard XSL and CSS style sheets to create good-looking online docs for your solution.


The C# compiler supports 16 different pre-defined XML comment elements, and they can be broken into three groups: basic XML comment elements, validated XML comment elements, and additional XML comment elements.


The basic elements include <summary>, <example>, <code>, and <remarks>. These are the major kinds of inline commenting for most code. FIGURE 1 shows how you can use some of the basic elements to comment a typical C# class module.



A simple method that adds two strings

/// together and returns a single string.


/// This sample shows how to call the

/// addSomeStringData method.


/// class MyClass

/// {

///    public static int Main()

///    {

///       string p1="part1";

///       string p2="part2";

///       System.Console.WriteLine(

///           addSomeStringData(p1,p2)

///       );

///      }

///   }



public string addSomeStringData(

              string part1, string part2)


    try {

        return part1 + ", " + part2;


    catch(FirstException exc) {

        return exc.Message;



FIGURE 1: Using the basic XML comment elements to comment a C# class.


You'll notice that each comment line starts with three forward slashes (///). This indicates to the compiler that a documentation comment is about to appear. Then, you can see that each major block of text in the comment space is surrounded by one or more XML elements. These are some of the pre-defined elements you can use in your comments.


The second group of XML comment elements is the validated group. This group contains pre-defined XML comment elements the C# compiler actually checks to make sure the comments are in synch with the code they describe. The XML elements in this group are <param>, <seealso>, <exception>, <permission>, <paramref>, and <see>. The first four items are block items that stand alone (like a paragraph). The last two (<paramref> and <see>) are in-line items that can appear with any comment text on the page.


For example, you can use the <param> element to define the parameters of your method signature. When you use this validated XML comment element in your code, the C# compiler will check the <param> elements against the associated method and report a compiler error if the comments and the code do not agree. Here's a class that uses the <param> XML comment element:



A simple method that returns

/// the uppercase version of any string you

/// pass into the method.

/// the string you wish to

/// convert to uppercase

public string getUpperData(string data) {

    return data.ToUpper();



When the compiler generates the actual code and metadata for this class, it will check the comment element and the method signature to make sure they match. This is a great way to make sure your documentation does not stray from the actual running code.


Finally, there are a handful of other XML comment elements you can use in your code. These allow you to create lists, mark paragraphs, note in-line code, and return values with different font styles. The XML comment elements in this group include: , < see>, < list>, <para>, < returns>, and < value>. Notice the use of the element. This in-line element denotes that the enclosed text should appear as source code in the display. Here's an example of how to use these additional XML comment elements to mark up your code:



Default constuctor

/// FirstClass has no parameters

/// for it's default constructor.

public FirstClass() {

    // na



FIGURE 2 contains an extended example that also demonstrates how to use the table-layout features of the XML comment elements.



FirstStruct is a sample structure

/// in C# that shows off the inline documenation

/// features of the .NET C# compiler.


/// Here are the structure properties

/// and their use:



///    Property

///    Comments



///    Name


///    The object's runtime name.




///    ID


///    The object's runtime ID

///    (always=13).





public struct FirstStruct { ... }

FIGURE 2: Using the XML comment elements to mark up a table display.


In FIGURE 2, you can see how to define rows and columns in a table as well as create the table-header row.


Adding code comments is commendable, but it can be tedious and can start to crowd out the actual execution code. There are two ways you can avoid comment-itis in your C# code. First, if you are using Visual Studio .NET to create your C# code, mark off the code-comment area with the #Region ... #End Region tags. This will tell the Visual Studio .NET editor to collapse these regions and move them out of view. You can still click on the outline's plus signs to expand the collapsed region any time you wish.


Also, you can store the actual code comments in a secondary file and only place references in your actual source code. This greatly reduces the clutter in your code and allows other, more experienced documentation specialists to edit and update your code comments without actually accessing your source code.


Here's an example of how you can use the <include> XML comment element to reference a section in an external XML documentation file within your source code:



///   file="sc.xml"

///   path="SecondClass/ItemList[@Name='constructor']/*"

/// />

public SecondClass() {

    // na



In this case, a file named sc.xml exists and contains a block element named ItemList with the Name attribute set to constructor. When the C# compiler runs, it will open that file, parse the XML to find the block element in question, and include that in the final XML output for the component.


A number of details about each XML comment element are worth exploring, but they're beyond the scope of this column. To learn more about the XML comment elements, look up /doc in the online help index for either the .NET Framework SDK or the Visual Studio .NET help files.


Generating the XML Output File

Once you know how to add XML comment elements to your code, you're ready to use the compiler to output these comments into a single XML file for use with help systems and with the Visual Studio .NET editor.


The simplest way is to use the command-line compiler with the /doc switch. This switch instructs the compiler to generate an XML file that includes all the XML comment elements, as well as some other basic XML information about the namespace, class, and methods in your code. For this article, I created a single cs file that held a base class, a derived class, and an exception class.


Below is the command line I used to compile the component and create the XML documentation file:


csc /target:library SS03Component.cs /doc:SS03Component.xml


The resulting output is an XML file that looks like the file in FIGURE 3.








FirstStruct is a sample structure

      in C# that shows off the inline documenation

      features of the .NET C# compiler.



FIGURE 3: A portion of the XML file created by the C# compiler.


Notice that additional information about the assembly and member names appears in the final XML file. This was generated by the C# compiler itself and can be used by third-party documentation tools, XSL and CSS style sheets, and by Visual Studio .NET as a way to control the visual markup and layout of the final document (more on that later).


You also can use Visual Studio .NET to generate the XML documentation files for you. All you need to do is set a special property of the project type to include the file name of the /doc option output file. To reach this dialog, select Project | Properties from the main menu in Visual Studio .NET and then select Configuration | Build Properties from the Property Pages dialog box to expose the list of possible outputs. Be sure to enter a valid file name for the XML output file. Then, press OK to save and dismiss the dialog. FIGURE 4 shows the dialog with the new /doc option file name completed.


FIGURE 4: Using the Project Properties dialog to control the name of the XML comment file created by Visual Studio .NET.


Now, when you build the Visual Studio .NET project, an additional file will be placed in the same folder as the dll or exe file your project produces. For example, in the case of a simple class library project, both the SS03Component.dll and the SS03Component.xml files are placed in the BIN\DEBUG folder of the project (see FIGURE 5).


FIGURE 5: Using Visual Studio's Solution Explorer window to inspect the hidden BIN folder for the generated XML comment file.


Styling the XML with XSL and CSS

Once you have generated the XML file with the C# compiler, you can use a number of techniques to turn it into a useful online document. One way to do this is to modify the file with XSL and CSS style sheets to output a printable, human-readable document you can use online or ship with your compiled project.


For this example, I created a very basic XSL transformation document and an accompanying CSS style sheet. FIGURE 6 shows the top-level transformation of that XSL transform file, doc.xsl.


<xsl:value-of select="doc/assembly/name"/>


FIGURE 6: An example of XSL used to transform the generated XML comment file into readable HTML.


The transform document in FIGURE 6 produces a standard HTML file that references a CSS style sheet for fonts and colors and then generates the body of the text using an apply-templates XSL element. The details of both the XSL and CSS files are not really relevant to this article, but they are included in the download files for this article, so you can look at them in greater detail on your own.


Once I have the XSL and CSS documents designed as I wish, I place a single line of code as the second line of the SS03Component.xml file as follows:



This line identifies the XSL style sheet to use to transform the pure XML into something readable. FIGURE 7 shows a sample output from the simple XSL/CSS transformation I created for the SS03Component.xml file.


FIGURE 7: Viewing the results of the XSL/CSS transformation of the generated XML comment file.


Using the XML File with Visual Studio .NET

In addition to using XSL and CSS to transform the XML file into readable text, you also can access the comment information from within Visual Studio .NET when you reference any component that has an associated XML documentation file. This means that any .NET assembly you distribute can have its own XML document associated with it, and that document will be used to help provide context information within Visual Studio .NET.


For example, the .NET assembly and the associated XML document file built earlier in this article were referenced in a Visual Studio .NET project using the standard Project | Add Reference dialog. Even though only the assembly DLL was seen and selected in the list of the dialog box, Visual Studio .NET also looks for and imports the associated XML document file into the project.


Now, when you load the SS03Component library in the Visual Studio .NET object browser, you can see the detailed descriptions from the XML document appearing in the text section of the object browser window (see FIGURE 8).


FIGURE 8: Using Visual Studio's object browser to read the XML comment data associated with the compiled assembly.


Generating Cool Online Docs with NDoc

Finally, you also can use third-party tools to convert your XML document into high-quality, online documentation. One example of this is the open-source tool NDoc. NDoc is built in C# and allows you to generate Microsoft-style help files that look and operate very much like the actual .NET Framework documentation. FIGURE 9 shows an example of the output from the same XML document I generated earlier.


FIGURE 9: An example of NDoc output created from the XML comment file generated by the C# compiler.


The process of generating online help files like the ones shown in FIGURE 9 is fairly simple with NDoc. All you do is start NDoc, locate and select the XML file generated by the compiler, and select the build option. Then, NDoc generates the entire help file, including any additional references to base-class documentation in the existing Microsoft documentation.


You can download the source code for NDoc from the Source Forge site at http://ndoc.sourceforge.net/.



Now that you have a basic idea of how the /doc feature of the C# compiler works, you can begin adding validated code comments to your source files. You can use them to generate simple HTML transformations, provide added support within Visual Studio .NET's object browser, and combine the output with third-party tools to generate high-quality help documents like those supplied with the .NET Framework SDK.


The files referenced in this article are available for download.


Mike Amundsen is currently the president, chief cook, and bottle-washer at EraServer.NET, a .NET hosting and XML Web Services company. He also heads a consulting firm, Amundsen.com, Inc. that enables clients to efficiently design, code, implement, and maintain successful .NET solutions. A well-known author and lecturer, Mike continues to travel the world teaching and speaking on .NET development issues. His latest book, with Paul Litwin, is ASP.NET for Developers from SAMS. He is also working on the fourth edition of Teach Yourself Database Programming with Visual Basic .NET in 21 Days and has more than a dozen other book titles to his credit. When he's not in the server room or on the road, Mike spends time with his family in and around their home in Northern Kentucky. Readers may contact Mike at mailto:[email protected].


Tell us what you think! Please send any comments about this article to [email protected]. Please include the article title and author.




Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.