Skip to main content

C# Documentation

Introduction

Documentation is a crucial aspect of software development that's often overlooked by beginners. Well-documented code is easier to understand, maintain, and collaborate on. In C#, documentation goes beyond simply adding comments - it includes structured XML documentation that integrates with Visual Studio's IntelliSense and can be used to generate external documentation.

In this guide, you'll learn how to effectively document your C# code using:

  • Basic code comments
  • XML documentation comments
  • Documentation best practices
  • Tools for generating documentation

Why Documentation Matters

Before diving into the "how," let's understand the "why":

  • Knowledge Sharing: Documentation helps team members understand code written by others
  • Future Reference: It helps you remember why you wrote code a particular way
  • Maintainability: Makes code easier to modify and debug months or years later
  • Integration: C# documentation integrates with IDE tools like IntelliSense
  • Professionalism: Well-documented code is a mark of a professional developer

Basic Code Comments

C# supports three types of comment styles:

Single-line Comments

Single-line comments start with // and continue until the end of the line:

csharp
// This is a single-line comment
int count = 10; // This comment is at the end of a line

Multi-line Comments

Multi-line comments start with /* and end with */:

csharp
/* This comment can span
multiple lines and is useful
for longer explanations */

XML Documentation Comments

These start with /// and are used for formal documentation:

csharp
/// <summary>
/// Calculates the sum of two integers.
/// </summary>
public int Add(int a, int b)
{
return a + b;
}

XML Documentation in C#

XML documentation is C#'s built-in system for documenting code. When you add XML comments to your code, Visual Studio's IntelliSense will display this information to other developers using your code.

XML Documentation Tags

Here are the most common XML tags used in C# documentation:

<summary>

Provides a brief description of a type or member:

csharp
/// <summary>
/// Represents a bank account with basic operations.
/// </summary>
public class BankAccount
{
// Class implementation
}

<param>

Describes a parameter for a method:

csharp
/// <summary>
/// Withdraws money from the account.
/// </summary>
/// <param name="amount">The amount to withdraw.</param>
public void Withdraw(decimal amount)
{
// Method implementation
}

<returns>

Describes the return value of a method:

csharp
/// <summary>
/// Calculates interest for the account.
/// </summary>
/// <returns>The calculated interest amount.</returns>
public decimal CalculateInterest()
{
// Method implementation
return balance * interestRate;
}

<exception>

Documents an exception that a method might throw:

csharp
/// <summary>
/// Withdraws money from the account.
/// </summary>
/// <param name="amount">The amount to withdraw.</param>
/// <exception cref="ArgumentException">Thrown when amount is negative.</exception>
/// <exception cref="InsufficientFundsException">Thrown when account has insufficient funds.</exception>
public void Withdraw(decimal amount)
{
// Method implementation
}

<remarks>

Provides additional information about a type or member:

csharp
/// <summary>
/// Represents a bank account.
/// </summary>
/// <remarks>
/// This implementation follows the banking regulations
/// established in 2022 and includes security measures
/// as specified in the security protocol document v3.2.
/// </remarks>
public class BankAccount
{
// Class implementation
}

<example>

Provides an example of how to use a method or class:

csharp
/// <summary>
/// Transfers money between accounts.
/// </summary>
/// <param name="toAccount">The destination account.</param>
/// <param name="amount">The amount to transfer.</param>
/// <example>
/// <code>
/// var sourceAccount = new BankAccount(1000);
/// var targetAccount = new BankAccount(0);
/// sourceAccount.Transfer(targetAccount, 500);
/// // sourceAccount.Balance is now 500
/// // targetAccount.Balance is now 500
/// </code>
/// </example>
public void Transfer(BankAccount toAccount, decimal amount)
{
// Method implementation
}

Real-World Example

Let's put this all together with a real-world example of a properly documented class:

csharp
using System;

namespace BankingSystem
{
/// <summary>
/// Represents a customer's bank account.
/// </summary>
/// <remarks>
/// This class provides basic banking operations like deposit,
/// withdrawal, and calculating interest.
/// </remarks>
public class BankAccount
{
private decimal balance;
private readonly decimal interestRate;
private readonly string accountNumber;

/// <summary>
/// Initializes a new instance of the <see cref="BankAccount"/> class.
/// </summary>
/// <param name="initialBalance">The starting balance of the account.</param>
/// <param name="interestRate">The annual interest rate as a decimal (e.g., 0.05 for 5%).</param>
/// <exception cref="ArgumentException">
/// Thrown when initialBalance is negative or interestRate is not positive.
/// </exception>
public BankAccount(decimal initialBalance, decimal interestRate)
{
if (initialBalance < 0)
throw new ArgumentException("Initial balance cannot be negative.", nameof(initialBalance));

if (interestRate <= 0)
throw new ArgumentException("Interest rate must be positive.", nameof(interestRate));

this.balance = initialBalance;
this.interestRate = interestRate;
this.accountNumber = GenerateAccountNumber();
}

/// <summary>
/// Gets the current account balance.
/// </summary>
/// <value>The current balance in the account.</value>
public decimal Balance => balance;

/// <summary>
/// Gets the account number.
/// </summary>
/// <value>The unique account identifier.</value>
public string AccountNumber => accountNumber;

/// <summary>
/// Deposits money into the account.
/// </summary>
/// <param name="amount">The amount to deposit.</param>
/// <exception cref="ArgumentException">
/// Thrown when the amount is not positive.
/// </exception>
/// <example>
/// <code>
/// var account = new BankAccount(100, 0.05m);
/// account.Deposit(50);
/// Console.WriteLine(account.Balance); // Outputs: 150
/// </code>
/// </example>
public void Deposit(decimal amount)
{
if (amount <= 0)
throw new ArgumentException("Deposit amount must be positive.", nameof(amount));

balance += amount;
}

/// <summary>
/// Withdraws money from the account.
/// </summary>
/// <param name="amount">The amount to withdraw.</param>
/// <returns>True if the withdrawal was successful, false otherwise.</returns>
/// <exception cref="ArgumentException">
/// Thrown when the amount is not positive.
/// </exception>
public bool Withdraw(decimal amount)
{
if (amount <= 0)
throw new ArgumentException("Withdrawal amount must be positive.", nameof(amount));

if (balance >= amount)
{
balance -= amount;
return true;
}

return false;
}

/// <summary>
/// Calculates interest on the current balance.
/// </summary>
/// <param name="months">Number of months to calculate interest for.</param>
/// <returns>The interest amount earned.</returns>
public decimal CalculateInterest(int months)
{
return balance * interestRate * months / 12;
}

/// <summary>
/// Applies earned interest to the account balance.
/// </summary>
/// <param name="months">Number of months of interest to apply.</param>
/// <returns>The amount of interest added to the account.</returns>
public decimal ApplyInterest(int months)
{
decimal interest = CalculateInterest(months);
balance += interest;
return interest;
}

/// <summary>
/// Generates a unique account number.
/// </summary>
/// <returns>A new account number string.</returns>
private string GenerateAccountNumber()
{
// Simple implementation for example purposes
return Guid.NewGuid().ToString("N").Substring(0, 10).ToUpper();
}
}
}

Generating Documentation

Once you've added XML documentation to your code, you can generate external documentation:

1. Enable XML Documentation File

In Visual Studio:

  1. Right-click your project in Solution Explorer
  2. Select "Properties"
  3. Go to "Build" tab
  4. Check "XML documentation file"
  5. Specify the path for the XML file (typically bin\Debug\YourProject.xml)

2. Using Documentation Generation Tools

Several tools can convert your XML documentation into readable formats:

  • DocFX: An open-source documentation generator for .NET projects
  • Sandcastle: Microsoft's documentation compiler
  • Doxygen: Cross-platform documentation generator

Example using DocFX (after installation):

bash
docfx init -q
docfx build
docfx serve _site

This creates a website with your documentation that you can browse locally.

Documentation Best Practices

To make the most of your documentation efforts:

  1. Document "Why" Not Just "What": Explain the reasoning behind complex code
  2. Keep Documentation Updated: Outdated documentation can be worse than none
  3. Use Consistent Language: Maintain a consistent tone and terminology
  4. Document Edge Cases: Explain how functions handle unexpected inputs
  5. Don't Overdo It: Simple, self-explanatory code may not need extensive comments
  6. Use Code Examples: Show how to use complex functions
  7. Link Related Documentation: Reference other relevant parts of your codebase

Summary

Proper documentation is an investment in your code's future. In C#, combining XML documentation with meaningful comments creates a powerful system that:

  • Provides guidance in the IDE through IntelliSense
  • Can be compiled into standalone documentation
  • Makes your code more maintainable and professional
  • Helps new team members understand your code faster

By following the practices outlined in this guide, you'll create C# code that's not only functional but also accessible and maintainable for years to come.

Additional Resources

Exercises

  1. Add XML documentation to an existing class you've written
  2. Generate documentation for a small project using DocFX
  3. Review a teammate's code and suggest documentation improvements
  4. Document a complex algorithm explaining not just what it does but why certain approaches were chosen


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