Skip to content

C# Standards

This document outlines the standards for writing C# code at Defra. To ensure consistency and maintainability, we align with Microsoft's official C# standards and best practices.

Key Principles

  1. Alignment with Microsoft Standards:
  2. Follow Microsoft's official C# coding conventions for:
    • Naming conventions
    • Indentation
    • Code formatting
    • Linting
  3. Refer to the following resources:

  4. Modern C# Practices:

  5. Use modern C# features such as:
    • async/await for asynchronous programming.
    • Nullable reference types (string?) to avoid null reference exceptions.
    • Pattern matching for cleaner and more readable code.
    • Records for immutable data models.
  6. Avoid outdated practices and legacy patterns unless required for compatibility.

  7. SOLID Principles:

  8. Follow the SOLID principles to ensure your code is maintainable, scalable, and easy to understand. These principles are:
    • S - Single Responsibility Principle (SRP):
    • A class should have only one reason to change. Each class should focus on a single responsibility or functionality.
    • O - Open/Closed Principle (OCP):
    • Classes should be open for extension but closed for modification. This allows new functionality to be added without altering existing code.
    • L - Liskov Substitution Principle (LSP):
    • Subtypes must be substitutable for their base types without altering the correctness of the program.
    • I - Interface Segregation Principle (ISP):
    • A class should not be forced to implement interfaces it does not use. Large interfaces should be split into smaller, more specific ones.
    • D - Dependency Inversion Principle (DIP):
    • High-level modules should not depend on low-level modules. Both should depend on abstractions, often achieved through dependency injection.

For a detailed explanation of the issues with violating SOLID principles, refer to Microsoft's overview.

  1. Testing:
  2. Write unit tests for all business logic.
  3. Use mocking frameworks for dependency isolation.
  4. Focus on meaningful code coverage rather than arbitrary metrics.

Additional Resources

For further guidance, refer to the following Microsoft resources: