#22 – C# Comments and XML Document Comments

There are three types comments in C#:

  • Single line comment with // ...;
  • Multiple line comments with /* ... */;
  • XML Document comments with /// ...;

Single line and Multiple line comments are straightforward, they are ignored by compiler.

XML document comments are a special kind of comment because they can be processed by the compiler to generate an XML documentation file at compile time. The generated XML file can be used to show quick information about types or members in a IDE intelligence and also can be used to generate API reference document.

Generate XML File by XML Document comments

  • Add <GenerateDocumentationFile>true</GenerateDocumentationFile> element to the <PropertyGroup> section of your .csproj project file

Let’s demonstrate how to generate XML file with XML document comments, and note the single and multiple line comments are not been generated into the XML file.

Program.cs

using System;
using HelloWorld;

Console.WriteLine("Hello XML Document");

var test = new TestClass();
test.TestXMLDocument(1, 2);


TestClass.cs

using System;

namespace HelloWorld
{
    /// <summary>
    /// Brief information of the class.
    /// </summary>
    /// <remarks>
    /// Supplement the information of the class.
    /// </remarks>
    public class TestClass
    {
        /// <summary>
        /// Brief information of the method.
        /// </summary>
        /// <remarks>
        /// Supplement the information of the method.
        /// </remarks>
        /// <returns>
        /// Return the sum of two integers.
        /// </returns>
        public int TestXMLDocument(int a, int b)
        {
            return a + b;
        }

        // This is single line comment.
        public void TestSingleLineComment(string str)
        {
            Console.WriteLine(str);
        }

        /*
        * This is multiple line comments line 1.
        * This is multiple line comments line 2.
        */
        public void TestMultipleLineComment(string str)
        {
            Console.WriteLine(str);
        }
    }
}

Build the program and you will see the generated XML file alongside the generated assembly.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.