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.
// Good habits, not new syntaxNaming 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.
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.");
}
}Written and closed safely.The using statement ensures the StreamWriter is properly disposed of, even if an exception occurs.
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);
}
}
}Error: Divisor cannot be zeroValidating 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.
