Skip to main content

.NET Documentation

Introduction

Documentation is a critical aspect of software development that's often overlooked by beginners but becomes increasingly important as projects grow in size and complexity. In the .NET ecosystem, good documentation practices not only help you understand your own code later, but also enable other developers to use your libraries and APIs effectively.

This guide covers how to document your .NET code properly, the tools available for generating documentation, and best practices to follow when documenting your .NET projects.

Why Documentation Matters

Before diving into the specifics of .NET documentation, let's understand why documentation is important:

  • Knowledge Preservation: Documentation captures your thought process and design decisions
  • Onboarding: Helps new team members understand code faster
  • Maintenance: Makes future maintenance easier, even for yourself
  • Collaboration: Enables effective teamwork
  • API Usability: Well-documented APIs are easier to use correctly

XML Documentation Comments in C#

The most basic form of documentation in .NET is writing XML comments directly in your C# code. These comments are processed by the compiler and can be used to generate documentation files.

Basic XML Documentation Syntax

To create XML documentation, use triple forward slashes (///) before a member:

csharp
/// <summary>
/// Calculates the sum of two integers.
/// </summary>
/// <param name="a">First integer to add</param>
/// <param name="b">Second integer to add</param>
/// <returns>The sum of the two integers</returns>
public int Add(int a, int b)
{
return a + b;
}

Common XML Tags

Here are the most common XML documentation tags:

  • <summary>: Provides a brief description of the type or member
  • <param>: Documents a parameter
  • <returns>: Documents the return value
  • <remarks>: Adds additional information about the type or member
  • <example>: Provides an example of using the type or member
  • <exception>: Documents exceptions that may be thrown
  • <see>: Creates a link to another member or type
  • <seealso>: Adds a "See Also" entry

Example with Multiple Tags

Here's a more comprehensive example:

csharp
/// <summary>
/// Divides two numbers and returns the result.
/// </summary>
/// <param name="dividend">The number to be divided.</param>
/// <param name="divisor">The number to divide by.</param>
/// <returns>The quotient of the division.</returns>
/// <exception cref="DivideByZeroException">
/// Thrown when <paramref name="divisor"/> is 0.
/// </exception>
/// <example>
/// <code>
/// double result = Calculator.Divide(10, 2); // Returns 5
/// </code>
/// </example>
/// <remarks>
/// This method performs standard division with no rounding.
/// </remarks>
public double Divide(double dividend, double divisor)
{
if (divisor == 0)
{
throw new DivideByZeroException("Cannot divide by zero.");
}

return dividend / divisor;
}

Enabling XML Documentation Files

To generate XML documentation files when compiling your project, you need to enable it in your project file:

For .NET Core/5/6+ Projects

Add the following to your .csproj file:

xml
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

For Older .NET Framework Projects

In Visual Studio:

  1. Right-click on the project in Solution Explorer
  2. Select "Properties"
  3. Go to the "Build" tab
  4. Check "XML documentation file"

Documentation Generation Tools

XML comments are helpful when viewing code, but to create proper documentation websites or files, you'll need additional tools:

DocFX

DocFX is a powerful documentation generation tool for .NET projects.

Basic DocFX Setup

  1. Install DocFX:
bash
dotnet tool install -g docfx
  1. Initialize a DocFX project:
bash
docfx init -q
  1. Build the documentation:
bash
docfx docfx.json
  1. Serve the documentation locally:
bash
docfx serve _site

Sandcastle

Sandcastle is another tool for generating documentation from XML comments. It's been around longer than DocFX but can be more complex to set up.

Documentation in Visual Studio

Visual Studio provides intellisense support for your XML documentation, showing tooltips with your documentation when using your API:

![Visual Studio Documentation Tooltip]

API Documentation with Swagger/OpenAPI

When building web APIs with ASP.NET Core, Swagger/OpenAPI provides an excellent way to document your API endpoints.

Setting Up Swagger in ASP.NET Core

  1. Install the NuGet package:
bash
dotnet add package Swashbuckle.AspNetCore
  1. Configure Swagger in Program.cs (or Startup.cs for older projects):
csharp
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Add Swagger services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {
Title = "My API",
Version = "v1",
Description = "An API for my awesome service"
});

// Include XML comments
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
  1. Add XML documentation to your API controllers:
csharp
/// <summary>
/// Gets a list of all users in the system.
/// </summary>
/// <returns>A list of user information.</returns>
/// <response code="200">Returns the list of users</response>
/// <response code="401">If the user is not authorized</response>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[HttpGet]
public ActionResult<IEnumerable<User>> GetUsers()
{
// Implementation here
}

Documentation Best Practices

Do's

  1. Document public APIs thoroughly: Any public method or class should have at least a summary comment.
  2. Keep documentation updated: When changing code, update the documentation to match.
  3. Use clear, concise language: Be direct and avoid unnecessary words.
  4. Include examples: Practical examples help users understand how to use your API.
  5. Document edge cases and exceptions: Make it clear what happens in unusual circumstances.

Don'ts

  1. Don't state the obvious: /// <summary>Gets the name</summary> for a GetName() method adds no value.
  2. Don't let documentation become outdated: Incorrect documentation is worse than no documentation.
  3. Don't use slang or unclear terms: Documentation should be professional and easily understood.
  4. Don't forget about documentation for non-English speakers: Use simple language and avoid idioms.

Tips for Effective Documentation

  • Be consistent: Use the same style and tone throughout your documentation.
  • Document the "why": Code shows what and how, documentation should explain why.
  • Use diagrams when appropriate: Sometimes a picture is worth a thousand words.
  • Consider accessibility: Make sure your generated documentation is accessible to all users.

Documentation as Part of the Development Process

Documentation shouldn't be an afterthought. Integrate it into your development process:

  1. Write documentation as you code: It's easier than trying to add it later.
  2. Review documentation during code reviews: Ensure accuracy and completeness.
  3. Add documentation requirements to your Definition of Done: A feature isn't complete until it's documented.
  4. Automate documentation validation: Use tools to check for missing documentation.

Real-World Example: A Well-Documented Library

Let's look at a more comprehensive example of documenting a simple library class:

csharp
namespace MyLibrary
{
/// <summary>
/// Provides methods for common string operations.
/// </summary>
/// <remarks>
/// This class contains utility methods for string manipulation
/// that aren't available in the standard String class.
/// </remarks>
public static class StringUtils
{
/// <summary>
/// Truncates a string to a specified length and adds an ellipsis (...) if truncated.
/// </summary>
/// <param name="input">The string to truncate.</param>
/// <param name="maxLength">The maximum length of the returned string, including the ellipsis if added.</param>
/// <param name="addEllipsis">Whether to add an ellipsis when truncating. Default is true.</param>
/// <returns>
/// The truncated string, with an ellipsis if specified and if truncation occurred.
/// If the original string is shorter than maxLength, it is returned unchanged.
/// </returns>
/// <exception cref="ArgumentNullException">Thrown when input is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when maxLength is less than 1.</exception>
/// <example>
/// <code>
/// string result1 = StringUtils.Truncate("Hello, world!", 5); // Returns "He..."
/// string result2 = StringUtils.Truncate("Hello", 10); // Returns "Hello"
/// string result3 = StringUtils.Truncate("Hello, world!", 5, false); // Returns "Hello"
/// </code>
/// </example>
public static string Truncate(string input, int maxLength, bool addEllipsis = true)
{
if (input == null)
throw new ArgumentNullException(nameof(input));

if (maxLength < 1)
throw new ArgumentOutOfRangeException(nameof(maxLength), "Maximum length must be at least 1.");

if (input.Length <= maxLength)
return input;

const string ellipsis = "...";

if (addEllipsis)
{
int truncateLength = maxLength - ellipsis.Length;
if (truncateLength < 0) truncateLength = 0;
return input.Substring(0, truncateLength) + ellipsis;
}

return input.Substring(0, maxLength);
}
}
}

Summary

Documentation is a crucial part of any .NET project, whether it's a small personal library or a large enterprise application. Good documentation makes your code more maintainable, helps onboard new developers, and improves the usability of your APIs.

In .NET, you have several tools at your disposal:

  • XML comments for documenting your code directly
  • DocFX and Sandcastle for generating documentation websites
  • Swagger/OpenAPI for documenting web APIs

By following best practices and integrating documentation into your development workflow, you can ensure that your .NET projects are well-documented and accessible to all developers who work with your code.

Further Resources

Practice Exercises

  1. Add proper XML documentation to an existing class in one of your projects.
  2. Set up DocFX for a .NET solution and generate documentation.
  3. Create an ASP.NET Core Web API project and configure Swagger documentation.
  4. Review an open-source .NET library to see how they handle documentation.
  5. Write a documentation review checklist for your team to use during code reviews.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)