Chapter 11: Extension methods
In this chapter
- 11.1 Why extension methods?
- Pain points of traditional static helper classes
- Advantages of extension methods
- 11.2 Extension method syntax
- Basic syntax: the
thiskeyword - How do you determine the receiver type?
- Extending interfaces
- Parameter passing rules
- Basic syntax: the
- 11.3 Extension method best practices
- Do not pollute core namespaces
- Choose the receiver type that fits the requirement
- Use generic extensions to improve reusability
- Ensure null safety
- Performance considerations
- 11.4 Extension members (C# 14)
extensionblock- Extension indexers (C# 15)
- Static extension members
- Practical example: adding extension properties to
DateTime
- 11.5 Priority and conflict resolution
- Instance methods take priority over extension methods
- Conflicts between extension methods
- Importance of namespaces
- Demoting extension methods
- 11.6 Application of local functions in extension methods
- Core application: iterator parameter validation split
- 11.7 Practical examples
- Fluent API design
- Extending LINQ
- Making existing types support
foreach(duck typing) - Smart parameter validation (CallerArgumentExpression)
- AI-assisted development: refactor to extension methods
- Summary
- Glossary
This chapter is not available in the free preview. Purchase the book to read the complete edition now.