*
C#/.NET Core Coding Guidelines
|
|
C#/.NET Core Coding Guidelines
1. General Principles
- Write clean, readable, and maintainable code.
- Favor clarity over cleverness.
- Stick to consistent conventions within the team/project.
- Follow the Microsoft .NET coding conventions.
2. Naming Conventions
- Use PascalCase for classes, methods, properties, constants.
- Use camelCase for local variables, parameters, private fields (prefix with underscore for private fields).
- Avoid all caps for acronyms (e.g., HttpClient not HTTPClient).
3. Code Structure
- One class per file (unless inner classes make sense).
- Keep files small and focused.
- Group related classes in namespaces.
- Use regions only when necessary.
4. Classes & Methods
- Keep classes small and cohesive (Single Responsibility Principle).
- Methods should be short and do one thing well.
- Use clear method names.
- Prefer async/await for I/O operations.
5. Comments & Documentation
- Use XML documentation comments (///) for public APIs.
- Comment why, not what.
- Keep comments up-to-date.
- Avoid unnecessary comments if code is self-explanatory.
6. Error Handling
- Use exceptions for exceptional cases, not control flow.
- Catch specific exceptions, not general Exception.
- Log exceptions with enough context.
- Use custom exception classes when needed.
7. Coding Style
- Indentation: 4 spaces (no tabs).
- Line length: aim for 120 characters max.
- Use expression-bodied members for simple properties/methods.
- Use string interpolation instead of concatenation.
8. LINQ & Collections
- Prefer LINQ for readability.
- Use var when the type is obvious, otherwise explicit.
- Avoid premature optimization with LINQ (measure performance first).
9. Dependency Injection (DI)
- Use constructor injection over property injection.
- Register services with appropriate lifetime (Singleton, Scoped, Transient).
- Avoid service locators in business logic.
10. Asynchronous Programming
- Use async/await with Task or ValueTask.
- Do not block async code with .Result or .Wait().
- Use ConfigureAwait(false) in library code (not needed in ASP.NET Core apps).
11. Unit Testing
- Write unit tests for business logic.
- Use naming convention: MethodName_StateUnderTest_ExpectedBehavior.
- Keep tests independent and repeatable.
- Use mocking frameworks (e.g., Moq) for dependencies.
12. Security & Performance
- Never store secrets in code (use Secret Manager or Azure Key Vault).
- Validate user inputs (never trust client-side data).
- Use IAsyncEnumerable for streaming data.
- Use Span and Memory in performance-critical paths.
13. Project Structure
/src
/MyApp.Api
/MyApp.Application
/MyApp.Domain
/MyApp.Infrastructure
/tests
/MyApp.UnitTests
/MyApp.IntegrationTests
- Separate concerns: API, business logic, domain models, persistence, etc.
- Follow Clean Architecture or Onion Architecture where possible.
*