.NET Guidelines

Introduction

This document provides a comprehensive, interactive guide to .NET coding standards. The goal is to establish a clear set of best practices for writing high-quality, maintainable, secure, and performant code. Use the navigation to quickly jump to the section you need. Each section explains the purpose of the guidelines and provides interactive code examples that you can copy directly.

1. Naming Conventions

This section outlines the standard naming conventions for .NET. Consistent naming is crucial for code readability and maintainability, as it allows developers to understand the purpose of a variable, method, or class just by looking at its name. Click on the code examples to copy them.

1.1 PascalCase

  • Classes, Structs, Enums, Interfaces, Delegates: `MyClass`, `UserAccount`
  • Public Methods: `CalculateTotal()`, `ProcessOrder()`
  • Properties: `UserName`, `ProductPrice`

1.2 camelCase

  • Local Variables: `userName`, `orderId`
  • Method Parameters: `string userName`, `int orderId`
  • Private Fields: `_customerName`, `_totalAmount`

1.3 Other Conventions

  • Interfaces: Prefix with `I`, e.g., `ICustomerRepository`
  • Constants (const fields): PascalCase, e.g., `MaxRetries`
  • Generic Type Parameters: Prefix with `T`, e.g., `TItem`

2. Code Formatting

Consistent code formatting ensures that the codebase is visually organized and easy to read for all team members. This section covers the standard rules for indentation, bracing, whitespace, and more, which helps to reduce cognitive load when reviewing or debugging code.

2.1 Indentation and Bracing

Use 4 spaces for indentation and always use braces, even for single-line statements, to prevent ambiguity and potential bugs.


// Good: Allman style braces and braces for single-line if
public class MyClass
{
    public void MyMethod(bool condition)
    {
        if (condition)
        {
            DoSomething();
        }
    }
}

// Bad: Braces omitted
if (condition)
    DoSomething();

2.2 Whitespace

Use whitespace logically to separate operators and code blocks, improving readability.


// Good: Proper spacing
int total = price + tax;
MyMethod(param1, param2);

// Bad: Inconsistent spacing
int total=price+tax;
MyMethod( param1,param2 );

2.3 Comments

Use XML comments for public APIs and inline comments for complex logic. Avoid comments that just restate the code.


/// <summary>
/// Calculates the total price for an order.
/// </summary>
/// <param name="orderId">The ID of the order.</param>
/// <returns>The calculated total price.</returns>
public decimal CalculateTotalPrice(int orderId)
{
    // Complex business logic explanation here
    // ...
}

3. Secure Coding Practices

This section provides critical guidelines for writing secure .NET code. Explore best practices for preventing common vulnerabilities like SQL injection and XSS, and learn how to handle user data safely. Use the interactive code examples to understand correct and incorrect implementations.

3.1 SQL Injection Prevention

Never concatenate user input into SQL queries. Always use parameterized queries or an ORM like Entity Framework.


// Good: Parameterized query
string sql = "SELECT * FROM Users WHERE UserName = @userName";
using (var command = new SqlCommand(sql, connection))
{
    command.Parameters.AddWithValue("@userName", userInput);
    // Execute command
}

// Bad: SQL Injection vulnerability
string badSql = "SELECT * FROM Users WHERE UserName = '" + userInput + "'";

3.2 Cross-Site Scripting (XSS) Prevention

Always encode user-supplied data before rendering it in HTML. ASP.NET Core Razor views do this automatically.

3.3 Input Validation

Validate all input on the server side for type, length, format, and range.

4. Resource Management

Properly managing unmanaged resources like database connections and file streams is essential for application stability and performance. This section explains how to use the `IDisposable` interface and `using` statements to ensure that resources are always released correctly.

4.1 `IDisposable` and `using` Statement

Always wrap objects that implement `IDisposable` in a `using` statement to guarantee their disposal.


// Good: DbConnection and DbCommand are automatically disposed
string connectionString = "YourConnectionString";
using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (var command = new SqlCommand("SELECT * FROM Users", connection))
    {
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                // Process data
            }
        } // reader is disposed
    } // command is disposed
} // connection is disposed

4.4 Connection Pooling

By using the `using` statement, you correctly open and close connections, which allows ADO.NET's connection pooling to work efficiently. Do not attempt to manage connection lifecycles manually.

5. General Best Practices

This final section covers high-level principles and practices that lead to robust, scalable, and maintainable applications. Following these guidelines, from writing unit tests to using dependency injection, will elevate the quality of your software architecture.

  • DRY (Don't Repeat Yourself): Avoid code duplication. Extract common logic into reusable methods or classes.
  • SOLID Principles: Adhere to Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion principles.
  • Unit Testing: Write comprehensive unit tests for all critical business logic to ensure correctness and prevent regressions.
  • Logging: Use a structured logging framework (e.g., Serilog, NLog) to log application events, errors, and warnings for easier debugging and monitoring.
  • Performance: Be mindful of performance. Use `StringBuilder` for string concatenation in loops and understand the performance implications of LINQ queries.
  • Dependency Injection: Use dependency injection to manage dependencies, which promotes loose coupling and makes code more modular and testable.
  • Code Reviews: Actively participate in code reviews to share knowledge, maintain standards, and catch issues early.

✨ Gemini Assistant

Have a question about .NET coding guidelines or best practices? Ask our AI assistant! It can provide clarifications, explanations, or additional insights to help you write better code.