CSharpHandbook
CSharpHandbook copied to clipboard
The focus of this document is on providing a reference for writing C#. It includes naming, structural and formatting conventions as well as best practices for writing clean, safe and maintainable code...
A C# Developer's Handbook
The focus of this document is on providing a reference for writing C#. It includes naming, structural and formatting conventions as well as best practices for writing clean, safe and maintainable code.
Many of the best practices and conventions apply equally well to other languages.
- Goals
- Scope
- Environment
- Improvements
- In Practice
- Table of Contents
- Overview
- Naming
- Formatting
- Usage
- Best Practices
Goals
This handbook has the following aims and guiding principles:
- Increase readability and maintainability with a unified style.
- Minimize complexity with proven design principles
- Increase code safety and prevent hard-to-find errors through best practices.
- Maximize effectiveness of coding tools.
- Accommodate IDE- or framework-generated code.
- Provide justifications and examples for rules.
Scope
This handbook includes:
- General programming advice and best practices
- General formatting and style recommendations
- C#-specific sections
Environment
The recommended environment and tools at this time are:
- Microsoft Visual Studio 2017
- JetBrains ReSharper 2016.3.2
- StyleCop 4.7
- StyleCop by JetBrains extension for ReSharper
- Cyclomatic Complexity extension for ReSharper
- EditorConfig
- C# 7.0
For older versions of Visual Studio and C#, use what you can or refer to older versions of this handbook.
Improvements
This document is a work-in-progress. Please speak up or contribute if you think there is something missing.
- If a guideline is not sufficiently clear, recommend a clearer formulation.
- If you don’t like a guideline, try to get it changed or removed, but don’t just ignore it. Your code reviewer is most likely unaware that you are special and not subject to the rules.
In Practice
Applying the Guidelines
- Unless otherwise noted, these guidelines are not optional, nor are they up to interpretation.
- A reviewer always has the right to correct mistakes and aberrations, but is not obligated to do so in every review.
- Please note issues with the guidelines during a review. These changes should flow into the guidelines if enough parties agree.
The handbook defines the goal. Use iterations and refactoring to incrementally bring the code closer to full compliance.
Fixing Problems in Code
Fix non-conforming code at the earliest opportunity.
- Fix small and localized errors immediately, in a "cleanup" commit.
- Always use a separate commit to rename or move files.
- Create an issue for larger problems that cannot be fixed quickly.
Working with an IDE
Modern IDEs generate code; this is very helpful and saves a lot of work. Within reason, the generated code should satisfy the coding guidelines. If the generated code is not under your control, then it's OK to turn a blind eye to style infractions.
- Configure your IDE to produce code that is as close to the guidelines as possible. StyleCop and ReSharper are an enormous help.
- Update names for visual-design elements and event handlers manually, if needed.
- Write code generators to produce conforming code.
- Do not update code generated by tools not under your control (e.g. *.Designer files).
- Use “Format Document” to reformat auto-generated code.
- Use the highest warning level available (level 4 in Visual Studio) and address all warnings (either by fixing the code or explicitly ignoring them).
Settings files
This repository includes configuration files that set up the rules outlined in this handbook for StyleCop and ReSharper and EditorConfig.
Table of Contents
Overview
- Terminology
- History
- References
Naming
- Characters
- Words
- Semantics
- Case
- Grouping
- Algorithm
- Structure
- Assemblies
- Files
- Namespaces
- Types
- Classes
- Interfaces
enums- Generic Parameters
- Sequences and Lists
- Members
- Properties
- Methods
- Extension Methods
- Parameters
- Lambdas
- Events
- Delegates
- Statements and Expressions
- Local Variables
- Return Values
- Compiler Variables
Formatting
- Whitespace and Symbols
- Blank Lines
- Line Breaks
- Indenting and Spacing
- Braces
- Parentheses
- Language Elements
- Methods
- Constructors
- Initializers
- Lambdas
- Multi-line Text
returnStatementsswitchStatements- Ternary & Coalescing Operators
- Comments
- Regions
Usage
- Structure
- Assemblies
- Files
- Namespaces
- Types
- Classes
- Abstract
- Static
- Inner
- Partial
- Interfaces
- Generics
structsenums
- Classes
- Members
- Modifiers
sealedinternal
- Declaration Order
- Constants
- Constructors
- Properties
- Indexers
- Methods
- Extension Methods
- Parameters
- Optional Parameters
- Expression-bodied Members
tuples- Overloads
- Virtual
newProperties- Event Handlers
- Operators
refReturns and Properties
- Modifiers
- Statements and Expressions
basethis- Value Types
- Strings
- Interpolation
nameof- Resource Strings
- Floating Point and Integral Types
- Local Variables
- Local Functions
varoutvariables- Loops
- Conditions
switch- Pattern-matching
continuereturngotounsafe- Ternary and Coalescing Operators
- Null-conditional Operator
throw-Expressions- Lambdas
- System.Linq
- Casting
checked- Compiler Variables
- Comments
Best Practices
- Design
- Abstractions
- Inheritance vs. Composition
- Interfaces vs. Abstract Classes
- Open vs. Closed APIs
- Controlling API Size
- Read-only Interfaces
- Single-Responsibility Principle
- Loose vs. Tight Coupling
- Methods vs. Properties
- Code > Comments
- Safe Programming
- Be Functional
- Avoid
nullreferences - Local variables
- Side Effects
- ”Access to Modified Closure”
- "Collection was modified; enumeration operation may not execute."
- "Possible multiple enumeration of IEnumerable"
- Error Handling
- Strategies
- Terms
- Errors
- Bugs
- Design-by-Contract
- Throwing Exceptions
- Catching Exceptions
- Defining Exceptions
- The Try* Pattern
- Error Messages
- Object Lifetime
IDisposableFinalize- Destructors
- Best Practices
- Managing Change
- Modifying Interfaces
- Marking Members as Obsolete
- Refactoring Names and Signatures
- Roadmap for Safe Obsolescence
- Documentation
- Files
- Language
- Style
- XML Documentation
- Examples
- Miscellaneous
- Generated Code
- Configuration and File System
- Logging
ValueTask<T>