C# and XML

In this conclusion to a ten-part series on C#, we start with attributes, but you will also learn about XML documentation and XML tags. This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Contributed by
Rating: 3 stars3 stars3 stars3 stars3 stars / 5
November 20, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Conditional Attributes

An attribute decorated with the Conditional attribute will be compiled only if a given preprocessor symbol is present. For example:

  // file1.cs
  #define DEBUG
  using System;
  using System.Diagnostics;
 
[Conditional("DEBUG")]
 
public class TestAttribute : Attribute {}

 

  // file2.cs
  #define DEBUG
 
[Test]
  class Foo
  {
   
[Test]
   
private string s;
  }

The compiler will not incorporate the[Test]attributes if the DEBUG symbol is in scope for file2.cs.

Pragma Warning

The compiler generates a warning when it spots something in your code that seems unintentional. Unlike errors, warnings don’t ordinarily prevent your application from compiling.

Compiler warnings can be extremely valuable in spotting bugs. Their usefulness, however, is undermined when you get an excessive number of them. In a large application, maintaining a good signal-to-noise ratio is essential if the “real” warnings are to get noticed.

To this effect, the compiler allows you to selectively suppress warnings with the#pragma warningdirective. In this example, we instruct the compiler not to warn us about the fieldMessagenot being used:

  public class Foo
  {
   
static void Main() { }

    #pragma warning disable 414
    static string Message = "Hello";
   
#pragma warning restore 414
  }

Omitting the number in the#pragma warningdirective disables or restores all warning codes.

If you are thorough in applying this directive, you can compile with the/warnaserrorswitch—this tells the compiler to treat any residual warnings as errors.

XML Documentation

Documentation comments are composed of embedded XML tags. Documentation comments start with three slashes (///), and apply to a type or type-member definition.

You can also use/** /for documentation comments (notice the extra star), but this format is less supported by the IDE.

The compiler can extract the documentation comments and output an XML file. Since the compiler understands the source code, it is able to validate the comments for consistency and expands cross-references into fully qualified type IDs.

The XML documentation file can be placed in the same directory as the application or library. The Visual Studio .NET IDE will automatically load this XML file, such that the documentation is integrated with IntelliSense. If you’re producing a component library, you can use a tool such as NDoc or Sandcastle to produce HTML help files.

Here is an example of documentation comments for a type. If you’re using Visual Studio .NET, typing a///before a member automatically gets the IDE to prepopulate the summary and parameter tags. Within the documentation, starting a tag with<causes IntelliSense to give you a list of built-in XML documentation annotations.

  // Filename: DocTest.cs
  using System;

  class Test
  {
   
/// <summary>
   
/// The Foo method is called from
   
///   <see cref="Main">Main</see>
   
/// </summary>
   
/// <mytag>user defined tag info</mytag>
   
/// <param name="s">Description for s</param>
   
static void Foo(string s) { Console.WriteLine(s); }

    static void Main() { Foo("42"); }
  }

When run through the compiler using the/doc:<filename> command-line option, the following XML file is generated:

  <?xml version="1.0"?>
 
<doc>
   
<assembly>
     
<name>DocTest</name>
    </assembly>
    <members>
      <member name="M:Test.Foo(System.String)">
       
<summary>
       
The Foo method is called from
         
<see cref="M:Test.Main">Main</see>
        </summary>
        <mytag>user defined tag info</mytag>
        <param name="s">Description for s</param>
      </member>
    </members>
  </doc>

Every member with a documentation comment has a<member>tag with anameattribute that uniquely identifies the member. Thecref attribute in the<see>tag has been expanded to correctly refer to another code element. The custom documentation element<mytag>is just carried along with the member payload.

Predefined XML Tags

Here is a list of the predefined set of XML tags that can be used to mark up the descriptive text:

<summary>

<summary>description</summary>
This is the first thing you will see when IntelliSense shows the tool tip for the member.

<remarks>

<remarks>description</remarks>
This is the additional text you will see when IntelliSense shows the tool tip for the member. This tag provides additional information regarding a particular member. Information about side effects within the method, or particular behavior that may not otherwise be intuitive (such as the idea that this method may throw anArrayOutOfBoundsExceptionif a parameter is greater than 5) is listed here.

<param>

<param name="name">description</param>
This tag describes a parameter on a method. If this tag is applied to any parameter on a method, all of the parameters on that method must be documented.

<returns>

<returns>description</returns>
This tag describes the return value for a method.

<exception>

<exception [cref="type"]>description</exception>
This tag documents the exceptions a method may throw. If present, the optionalcref attribute should refer to the type of the exception. The type name must be enclosed in double quotation marks ("").

<permission>

<permission [cref="type"]>description</permission>
This tag documents the permissions requirement for a type or member. If present, the optionalcrefattribute should refer to the type that represents the permission set required by the member, although the compiler does not validate this. The type name must be enclosed in double quotation marks ("").

<example>

<example>description</example>
This tag provides a description and sample source code explaining the use of a type or member. Typically, the<example>tag provides the description and contains the<c>and<code>tags, although they can also be used independently.

<c>

<c>code</c>
This tag indicates an inline code snippet. Typically, this tag is used inside an<example>block (described previously).

<code>

<code>code</code>
This tag is used to indicate multiline code snippets. Again, this is typically used inside an<example>block (described previously).

<see>

<see cref="member">text</see>
This tag identifies cross-references in the documentation to other types or members. Typically, the<see>tag is used inline within a description (as opposed to the<seealso>tag, which is broken out into a separate “See Also” section). This tag is useful because it allows tools to generate cross-references, indexes, and hyperlinked views of the documentation. Member names must be enclosed by double quotation marks ("").

<seealso>

<seealso cref="member">text</seealso>
This tag identifies cross-references in the documentation to other types or members. Typically,<seealso>tags are broken out into a separate “See Also” section. This tag is useful because it allows tools to generate cross-references, indexes, and hyperlinked views of the documentation. Member names must be enclosed by double quotation marks ("").

<value>

<value>description</value>
This tag describes a property on a class.

<paramref>

<paramref name="name"/>
This tag identifies the use of a parameter name within descriptive text, such as<remarks>. The name must be enclosed by double quotation marks ("").

<list>
    <list type=[ bullet | number | table ]>
     
<listheader>
        <term>name</term>
       <description>description</description>
      </listheader>
     
<item>
        <term>name</term>
      <description>description</description>
      </item
   </list>

This tag provides hints to documentation generators about how to format the documentation—in this case, as a list of items.

<para>

<para>text</para>
This tag sets off the text as a paragraph to documentation generators.

<include>

<include file='filename' path='path-to-element'>
This tag specifies an external file that contains documentation and an XPath path to a specific element in that file. For example, a path of
docs[@id="001"]/*retrieves whatever is inside<docs id="001"/>. Thefilenameandpathmust be enclosed by single quotation marks (''), but you must use double quotation marks ("") for theidattribute within thepath-to-elementexpression.

User-Defined Tags

There is little that is special about the predefined XML tags recognized by the C# compiler, and you are free to define your own. The only special processing done by the compiler is on the <param> tag (in which it verifies the parameter name and that all the parameters on the method are documented) and the cref attribute (in which it verifies that the attribute refers to a real type or member and expands it to a fully qualified type or member ID). The cref attribute can also be used in your own tags and is verified and expanded just as it is in the predefined <exception>, <permission>,<see>, and<seealso>tags.

Type or Member Cross-References

Type names and type or member cross-references are translated into IDs that uniquely define the type or member. These names are composed of a prefix that defines what the ID represents and a signature of the type or member.

Table 4-4 lists the set of type or member prefixes.

Table 4-4. XML type ID prefixes

XML type prefix

ID prefixes applied to

N

Namespace

T

Type (class, struct, enum, interface, delegate)

F

Field

P

Property (includes indexers)

M

Method (includes special methods)

E

Event

!

Error

The rules describing how the signatures are generated are well documented, although fairly complex.

Here is an example of a type and the IDs that are generated:

  // Namespaces do not have independent signatures
  namespace NS
  {
   
/// T:NS.MyClass
    class MyClass
    {
      /// F:NS.MyClass.aField
      string aField;

      /// P:NS.MyClass.aProperty
      short aProperty {get {...} set {...}}

      /// T:NS.MyClass.NestedType
      class NestedType {...};

      /// M:NS.MyClass.X()
      void X() {...}

      /// M:NS.MyClass.Y(System.Int32,System.Double@,System.Decimal@)
      void Y(int p1, ref double p2, out decimal p3) {...}

      /// M:NS.MyClass.Z(System.Char[ ],System.Single[0:,0:])
      void Z(char[ ] 1, float[,] p2) {...}

      /// M:NS.MyClass.op_Addition(NS.MyClass,NS.MyClass)
      public static MyClass operator+(MyClass c1, MyClass c2) {...}

      /// M:NS.MyClass.op_Implicit(NS.MyClass)~System.Int32
      public static implicit operator int(MyClass c) {...}

      /// M:NS.MyClass.#ctor
      MyClass() {...}

      /// M:NS.MyClass.Finalize
      ~MyClass() {...}

      /// M:NS.MyClass.#cctor
      static MyClass() {...}
    }
  }

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 10 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials