The next topic looks very simple on the
surface - adding comments to your code.
Internal Comments within the Source Files
As noted earlier in this chapter, C# uses the
traditional C-type single-line (// ...)
and multiline (/* ... */) comments:
Everything in a single-line comment, from the
// to the end of the line, will be
ignored by the compiler, and everything from an opening
/* to the next */ in a multiline comment combination will be
ignored. Obviously, you can’t include the combination */ in any multiline comments, because this will be
treated as the end of the comment.
It is actually possible to put multiline comments
within a line of code:
Inline comments like this should be used with care
because they can make code hard to read. However, they can be
useful when debugging if, say, you temporarily want to try running
the code with a different value somewhere:
Comment characters included in string literals are,
of course, treated like normal characters:
XML Documentation
In addition to the C-type comments,
illustrated in the preceding section, C# has a very neat feature
that we can’t omit from this chapter: the ability to produce
documentation in XML format automatically from special comments.
These comments are single-line comments but begin with three
slashes (///), instead of the usual two.
Within these comments, you can place XML tags containing
documentation of the types and type members in your code.
The tags in the following table are recognized by
the compiler.
To see how this works, add some XML comments to the
MathLibrary.cs file from the “More on
Compiling C# Files” section, and call it Math.cs. You will add a <summary> element for the class and for its
Add() method, and also a <returns> element and two <param> elements for the Add() method:
The C# compiler can extract the XML elements from
the special comments and use them to generate an XML file. To get
the compiler to generate the XML documentation for an assembly, you
specify the /doc option when you
compile, together with the name of the file you want to be
created:
The compiler will throw an error if the XML
comments do not result in a well-formed XML document.
This will generate an XML file named Math.xml, which looks like this:
Notice how the compiler has actually done some
work for you; it has created an <assembly> element and also added a
<member> element for each type or
member of a type in the file. Each <member> element has a name attribute with the full name of the member as
its value, prefixed by a letter that indicates whether this is a
type (T:), field (F:), or member (M:).