C# - Do's and Don'ts
Writing C# code is not just about making it work; it's about making it clean, efficient, and easy for you and others to maintain. Following these best practices and avoiding common pitfalls will help you write professional, high-quality applications.
✅ Do's: The Best Practices
Use Meaningful Names: Naming is one of the most important aspects of readable code. Use descriptive names for variables, classes, and methods. Follow standard C# naming conventions:
camelCasefor local variables and parameters, andPascalCasefor public methods, classes, and properties.Embrace
async/await: Use theasyncandawaitkeywords for asynchronous operations to prevent blocking the UI or other threads. This is crucial for I/O-bound tasks like database queries and web requests, ensuring your application remains responsive.Leverage LINQ: Use Language Integrated Query (LINQ) to query data from collections, databases, and XML in a type-safe and highly readable manner. This declarative approach simplifies complex data manipulation.
Use Dependency Injection: This design pattern helps create loosely coupled, testable, and maintainable code. It allows you to inject dependencies into a class rather than having the class create them itself.
Use
varfor Local Variables: When the type is obvious from the right-hand side of the assignment (e.g.,var myString = "hello";), using thevarkeyword can make your code more concise without sacrificing readability.Use Modern C# Features: Keep your skills up to date by using newer language features like pattern matching, nullable reference types, and expression-bodied members to write more expressive and efficient code.
Follow the Principle of Least Privilege: Restrict the accessibility of your members (e.g., using
privateorinternal) to only what's necessary. This encapsulates functionality and reduces the risk of unintended access or modification.
❌ Don'ts: The Common Pitfalls
Avoid an Empty
catchBlock: Hiding an exception with an emptycatchblock is a major anti-pattern. It prevents you from knowing when something has gone wrong and makes debugging a nightmare. At the very least, you should log the exception.Don't Use
goto: Thegotostatement can create code with a tangled, complex control flow that's hard to follow. It leads to spaghetti code, where logic jumps around the function, making it impossible to read from top to bottom. Use loops, conditional statements, and well-structured methods instead. * Avoid Creating Long Methods: Long methods are hard to read, test, and maintain. Break down complex logic into smaller, more focused methods that perform a single task. This aligns with the Single Responsibility Principle.Don't Ignore Compiler Warnings: Treat compiler warnings as hints about potential issues. They are often indicators of code that could lead to bugs, performance problems, or security vulnerabilities. Resolve them to ensure your code is robust.
Don't Use Magic Strings or Numbers: These are values embedded directly into the code without explanation. Instead, use constants or enumerations to give them meaningful names. This improves readability and makes your code much easier to change later on.
Avoid Excessive Nested Loops and Conditionals: Deeply nested structures make code difficult to follow and debug. Consider refactoring with early returns or helper methods to flatten the code and improve its readability.
Avoid Overusing
new: Creating too many objects, especially in a loop, can be inefficient and put pressure on the garbage collector. Use dependency injection or object pooling where appropriate to manage object lifecycle more effectively.