| applyTo | **/*.cs |
|---|---|
| description | C# best practices and formatting guidelines for AI code generation (all versions). |
- Use file-scoped namespace declarations when using C# 10+ (
namespace MyNamespace;) - For older versions, use traditional block-scoped namespaces with proper indentation
- Keep namespace declarations consistent within the project
- Explicitly declare access modifiers for all members
- Use
readonlyfor fields that are only assigned in constructors - Use
constfor compile-time constants - Follow principle of least privilege for access levels
- Use
varfor local variables when the type is obvious from the right side - Use explicit types for method parameters, return types, and field declarations
- Prefer target-typed expressions when the type is clear from context
- Use meaningful and descriptive type names
- Use expression-bodied members for simple one-line implementations
- Place opening braces on new lines for methods, classes, and namespaces
- Use auto-implemented properties when appropriate
- Implement properties with backing fields only when additional logic is needed
- Use null-conditional operators (
?.,??,??=) when available - Validate parameters with appropriate null checks
- Use
string.IsNullOrEmpty()andstring.IsNullOrWhiteSpace()for string validation - Consider nullable reference types when using C# 8+
- Use string interpolation
$""instead ofString.Format()or concatenation - Use
StringBuilderfor extensive string manipulation - Prefer
string.Equals()withStringComparisonfor culture-aware comparisons - Use verbatim strings
@""for paths and multi-line strings
- Use specific exception types rather than generic
Exception - Implement proper exception filtering with
whenclauses when available - Provide meaningful exception messages
- Follow the fail-fast principle
- Dispose of
IDisposableobjects properly usingusingstatements or blocks - Avoid unnecessary boxing and unboxing
- Use appropriate collection types for the use case
- Consider object pooling for frequently allocated objects
- Use appropriate collection types:
List<T>,HashSet<T>,Dictionary<TKey, TValue> - Prefer
IEnumerable<T>for method parameters when only enumeration is needed - Use
IReadOnlyList<T>andIReadOnlyCollection<T>for immutable data exposure - Initialize collections with known capacity when possible
- Use LINQ methods appropriately for readability and performance
- Prefer method syntax over query syntax for simple operations
- Be aware of deferred execution implications
- Use
ToList()orToArray()when multiple enumeration is needed
- Use
async Taskfor void-returning async methods - Use
async Task<T>for value-returning async methods - Avoid
async voidexcept for event handlers - Use
ConfigureAwait(false)in library code
- Accept
CancellationTokenparameters in long-running async methods - Check for cancellation at appropriate intervals
- Pass cancellation tokens through the call chain
- Handle
OperationCanceledExceptionappropriately
- Keep fields private and expose through properties
- Use appropriate access modifiers to control visibility
- Validate property setters when necessary
- Hide implementation details behind interfaces
- Prefer composition over inheritance when appropriate
- Use virtual methods judiciously
- Override
Equals,GetHashCode, andToStringwhen meaningful - Implement interfaces explicitly when there might be naming conflicts
- Single Responsibility: Classes should have one reason to change
- Open/Closed: Open for extension, closed for modification
- Liskov Substitution: Subtypes must be substitutable for base types
- Interface Segregation: Many specific interfaces are better than one general
- Dependency Inversion: Depend on abstractions, not concretions
- Provide XML documentation comments for all public APIs
- Use
<summary>,<param>,<returns>, and<exception>tags appropriately - Include
<example>sections for complex methods - Document any thread safety considerations
- Use modern test frameworks like xUnit, NUnit, or MSTest
- Follow AAA pattern: Arrange, Act, Assert
- Use meaningful test method names that describe the scenario
- Test both happy path and edge cases
- Mock dependencies appropriately
- One public type per file
- File name should match the primary type name
- Organize using statements: System namespaces first, then third-party, then project namespaces
- Remove unused using statements
- Group related types in appropriate namespaces
- Follow Microsoft's .NET coding conventions
- Use EditorConfig files for consistent formatting across teams
- Enable and address code analysis warnings
- Use static analysis tools like SonarQube or Roslyn analyzers
- Implement code reviews and pair programming
- Use exceptions for exceptional circumstances, not control flow
- Catch specific exceptions rather than generic
Exception - Log errors appropriately without exposing sensitive information
- Provide meaningful error messages to users
- Consider using Result pattern for expected failures
- Implement
IDisposablefor types that manage unmanaged resources - Use
usingstatements for automatic resource cleanup - Follow the Dispose pattern correctly
- Consider implementing finalizers only when necessary
- Use appropriate logging frameworks
- Implement health checks for long-running services
- Monitor memory usage and garbage collection
- Profile applications to identify bottlenecks
- ALWAYS trim trailing whitespace from all lines after any code changes
- Ensure consistent line endings (LF on Unix, CRLF on Windows)
- Remove any extra blank lines at the end of files
- Ensure proper indentation (4 spaces for C#, no tabs)
- Format code according to project standards
- Validate all input parameters
- Use secure string handling practices
- Implement proper authentication and authorization
- Follow OWASP guidelines for secure coding practices
- Avoid hardcoding sensitive information
- Use secure communication protocols (HTTPS, TLS)
- Implement proper error handling without exposing sensitive information