C# Coding Standards

Follow these coding standards to write clean, maintainable, and efficient C# code.

Use Meaningful Names
Essential
Choose descriptive names for variables, methods, and classes that clearly express their purpose.

Recommended Approach

// Good
public class CustomerOrderProcessor
{
    private readonly IPaymentService _paymentService;
    
    public async Task<OrderResult> ProcessCustomerOrderAsync(Order order)
    {
        // Implementation
    }
}

Avoid This Approach

// Bad
public class COP
{
    private readonly IPS ps;
    
    public async Task<OR> ProcessAsync(O o)
    {
        // Implementation
    }
}
Follow C# Naming Conventions
Essential
Use PascalCase for public members, camelCase for private fields, and consistent naming patterns.

Recommended Approach

// Good
public class ProductService
{
    private readonly ILogger _logger;
    private const int MaxRetryAttempts = 3;
    
    public async Task<Product> GetProductByIdAsync(int productId)
    {
        // Implementation
    }
}

Avoid This Approach

// Bad
public class productservice
{
    private readonly ILogger Logger;
    private const int max_retry_attempts = 3;
    
    public async Task<Product> getproductbyid(int ProductID)
    {
        // Implementation
    }
}
Use Consistent Indentation
Essential
Maintain consistent indentation throughout your code to improve readability and maintainability.

Recommended Approach

// Good
public class Example
{
    public void Method()
    {
        if (condition)
        {
            // Do something
        }
    }
}

Avoid This Approach

// Bad
public class Example
{
public void Method()
{
if (condition)
{
// Do something
}
}
}
Limit Line Length
Important
Keep line length to a reasonable limit (e.g., 80-100 characters) to enhance code readability.

Recommended Approach

// Good
public class Example
{
    public void Method()
    {
        var longString = "This is a long string that is split " +
                         "across multiple lines for better readability.";
    }
}

Avoid This Approach

// Bad
public class Example
{
    public void Method()
    {
        var longString = "This is a long string that is not split across multiple lines, making it hard to read.";
    }
}
Avoid Magic Numbers
Important
Use named constants instead of magic numbers to make your code more understandable and maintainable.

Recommended Approach

// Good
public class Circle
{
    private const double Pi = 3.14159;
    public double CalculateCircumference(double radius)
    {
        return 2 * Pi * radius;
    }
}

Avoid This Approach

// Bad
public class Circle
{
    public double CalculateCircumference(double radius)
    {
        return 2 * 3.14159 * radius;
    }
}
Use Comments Wisely
Essential
Write comments to explain why code exists, not what it does. Keep comments up-to-date.

Recommended Approach

// Good
public class DataProcessor
{
    // This method processes data from the input stream and applies necessary transformations.
    public void ProcessData(Stream inputStream)
    {
        // Implementation
    }
}

Avoid This Approach

// Bad
public class DataProcessor
{
    // Process data
    public void ProcessData(Stream inputStream)
    {
        // Implementation
    }
}
Encapsulate Conditionals
Important
Encapsulate complex conditionals in methods to improve readability and maintainability.

Recommended Approach

// Good
public class Order
{
    public bool IsEligibleForDiscount(Customer customer)
    {
        return customer.IsLoyal && customer.TotalOrders > 10;
    }
}

Avoid This Approach

// Bad
public class Order
{
    public bool IsEligibleForDiscount(Customer customer)
    {
        return customer.IsLoyal && customer.TotalOrders > 10 && customer.HasCoupon;
    }
}
Use Exception Handling
Critical
Implement proper exception handling to manage errors gracefully and maintain application stability.

Recommended Approach

// Good
public class FileProcessor
{
    public void ProcessFile(string filePath)
    {
        try
        {
            // File processing logic
        }
        catch (IOException ex)
        {
            // Handle I/O exceptions
        }
    }
}

Avoid This Approach

// Bad
public class FileProcessor
{
    public void ProcessFile(string filePath)
    {
        // File processing logic without exception handling
    }
}
Implement Proper Error Logging
Critical
Use a consistent logging framework to log errors with sufficient context to aid in debugging.

Recommended Approach

// Good
public class UserService
{
    private readonly ILogger<UserService> _logger;

    public UserService(ILogger<UserService> logger)
    {
        _logger = logger;
    }

    public void CreateUser(User user)
    {
        try
        {
            // User creation logic
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error creating user {UserId}", user.Id);
        }
    }
}

Avoid This Approach

// Bad
public class UserService
{
    public void CreateUser(User user)
    {
        try
        {
            // User creation logic
        }
        catch (Exception)
        {
            Console.WriteLine("An error occurred.");
        }
    }
}