C# · Chapter 46 of 46

C# Best Practices

Writing good C# code goes beyond making it compile — it means writing code that is safe, readable, and maintainable. This includes using meaningful names, handling exceptions properly, and following consistent style conventions.

C# has well-established naming conventions (PascalCase for classes and methods, camelCase for local variables) and idioms (like using properties instead of public fields) that make code easier for other developers to understand.

Syntax
// Good habits, not new syntax

Naming and style

Use PascalCase for classes, methods, and properties (like CustomerAccount), and camelCase for local variables and parameters (like customerName). Keep methods short and focused on one task.

Safety and maintainability

Handle exceptions with specific catch blocks rather than catching everything generically. Use `using` statements to dispose of resources like file streams properly, and prefer immutability where practical.

Example 1 (csharp)
using System;
using System.IO;

class Program {
  static void Main() {
    using (StreamWriter writer = new StreamWriter("log.txt")) {
      writer.WriteLine("Log entry");
    }
    Console.WriteLine("Written and closed safely.");
  }
}
Output
Written and closed safely.

The using statement ensures the StreamWriter is properly disposed of, even if an exception occurs.

Example 2 (csharp)
using System;

class Program {
  static int Divide(int a, int b) {
    if (b == 0) throw new ArgumentException("Divisor cannot be zero");
    return a / b;
  }

  static void Main() {
    try {
      Console.WriteLine(Divide(10, 0));
    } catch (ArgumentException ex) {
      Console.WriteLine("Error: " + ex.Message);
    }
  }
}
Output
Error: Divisor cannot be zero

Validating input and throwing a clear, specific exception makes bugs easier to diagnose.

Key points

  • Use PascalCase for classes/methods/properties and camelCase for local variables.
  • Use `using` statements to safely dispose of resources like files and streams.
  • Catch specific exception types rather than a generic Exception.
  • Keep methods small, focused, and well-named for readability.
💡 Note: Consistent naming and clear structure make your C# code much easier for you and others to maintain over time.

📝 Quick Quiz

1. What naming convention is used for C# class names?

2. What does a `using` statement help ensure?

3. Why catch specific exception types instead of a generic Exception?