12 C#ExtensionMethods
12 C#ExtensionMethods
Extension metods:
- Extension methods let you extend the codebase by adding methods to types so you can take
an assembly, which you didn't compile, like the core.net framework assembly and a
namespace, which you don't own, like System, and a type, which you didn't write, like
DateTime, and add your own functionality to it. You can easily add custom logic, like
representing the date in a format used by a legacy system in your own extension method
- You can add extension methods to classes, structs, and interfaces
- You have to honor the visibility of the class you're extending, so for third-party assemblies
you can only extend public types, but you can't extend sealed classes
- You can also extend generic classes and interfaces and that makes extension methods
extremely powerful
- Extension methods are enablers for very common scenarios like:
o adding our own domain logic to a third-party codebase
o implementing logic in our own domain, which is frequently needed, but doesn't fit
within a normal class hierarchy. – enable technology adding to a class hierarchy
without inheritance and composition
- Extension methods are also simple to write and consume once you know the basic rules, but
they're a powerful way to make your solution richer without making it more complex
- Extension methods must be declared as static
Declaring Extension methods:
1
Summary:
How to write extension methods:
- to define an extension method you make it a static method in a static class with the first
argument be an instance of the type you want to extend, flagged with the this keyword.
What can you do with Extension Methods?
- adding functionality to an external codebase
- extending an existing hierarchy without using inheritance or composition
- adding aggregate functionality to collections without custom collection classes
- adding functionality to every object
Protable Extension Methods:
- Class Library extension methods
o Can be used anywhere with a valid reference
C# projects, Visual Basic projects, etc.
Not portable (Windows Store) projects
- Portable Class Library extension methods
o Can be used anywhere with a valid reference
Portable and non-portable C# projects, Visual Basic projects, etc.
- Targeted Class Library extension methods
o Can be used with the same (or higher) .NET framework
Except portable projects
o Including Client Profile targets
o Minimum framework version 3.5
How extension methods work? – compiler bindings to IL
Extension methods compiler binding:
- Generates IL for static call at build time
- Disambiguation rules:
o Extension methods for different types
Class methods called
o Extension methods for different types
Most specific called
o Multiple extension methods in scope
Compiler error
o No extension methods in scope
Compiler error