C# Extension Methods
You can write extension methods :
- for public types in the base class library - In a NuGet package library - In a project reference - In public and internal types if your sponsor class is the same project as your target class
Steps to create your own extension methods
1. Create new solution with the name of the namespace you want to create. 2. Use the "properties" menu to check you're using .NET Standard version 3. Use "Manage NuGet Packages" to add Microsoft.Extensions.Configuration, "".Primitives, and "".Abstractions to take advantage of existing functionality 4. Add a using statement for the namespace you want to use 5. Create a sponsor class
Extensions should be (3 qualities)
1. Discoverable - easy to discover 2. Deliberate - hard to use by mistake 3. Robust - resilient to breaking in the future
There are two ways to name your extension method namespace :
1. Name it the same as the target namespace, so that when the user implements a using statement for that namespace they get yours too 2. Use a custom namespace which users have to explicitly add
Larger company guidelines are prioritized slightly differently :
1. Robust 2. Deliberate 3. Discoverable
Cross-cutting code requires unit-test coverage of ____%
90+%
Wrapper class
A class which "wraps" or "encapsulates" the functionality of another class or component, often to provide a level of abstraction from the implementation of the underlying class.
Serilog
A library for .NET that provides diagnostic logging to files, the console, and elsewhere.
Prometheus
An extension library required by all modern apps for recording stats about how your app is performing
Encapsulation
An object's ability to hide data and behavior that are not necessary to its user
Feed
An ongoing stream of structured data
Cross-cutting code
Code that affects multiple parts of a system. This is a big concern that object-oriented programming attempts to fix.
How often should you create extension methods?
Create extension methods SPARINGLY.
DRY principle
Do not Repeat Yourself
Existing extensions for production readiness
Docker Kubernetes
When building packages to add to your GitHub, make sure to have a...
GitHub homepage that includes documentation for what your package contains, what it does, which types it works with
With your new solution for building extension methods, select "Manage NuGet Packages" to add NuGet package references to the ___________ libraries that we want to use for additional, pre-existing functionality.
Microsoft.Extensions.Configuration
Good general libraries available
MoreLinq Humanizer
When you create a new solution to build extension methods from, use the explorer to select the _______ menu, to be sure you're using the .NET version called ___________
Properties , .NET Standard
_________ is the key use of extension methods.
Reuse
SOLID principle
Single Responsibility Open-closed Liskov substitution Interface segregation Dependency inversion
_____________ are what drives documentations in your wikis for extension methods
XML comments
The best way to incorporate third party libraries into your library is to...
add the package to your project and wrap the relevant functionality from the package in your own class. This allows you to incorporate only the methods you need from the package and remove all the ones you don't need.
The type you're extending can be in any ______ but the type has to be ______
assembly , accessible
Custom namespaces are often _____ so users don't ...
better , bring your extension into scope accidentally
if you're only using the method in a single class, stick to _______
class methods
The method name should be _____ and ____ . Users should know ...
clear and explicit exactly what they're getting, especially if the extension method has entered scope unexpectedly.
Extension methods can be used as a time saver in two primary ways :
consolidating repetitive code in a single place, and centralizing null value checks
Regarding extension methods, larger companies often...
create global extension method libraries to be shared between projects
Make your sponsor class name _____ . Preferably use the convention that ...
descriptive , class names end with extensions
Regardless of where extension methods can be accessed, you should group extension methods into...
different assemblies, where each assembly has a defined scope.
Treat ________ as mandatory for your extension methods. Intellisense will show...
documentation , XML comments in your extension, so make sure you include a summary that is clear for what the extension does
Grouping extension methods into different assemblies helps to...
ensure extensions aren't used by mistake, because it requires the user to add references to teach specific assembly rather than a global assembly
Extension methods let you
extend an existing class or interface into your own code or someone else's code using a single implementation of a method, which is easily discoverable
The leading strategy for organizing extension methods is to...
have 1 core package with core functionality, the nadd packages for variations that you support
Under the hood, extension methods are really just
helper methods built into classic utility classes
Abstraction use case
if you have a class for calculating EngineerSalary and you want engineers to manage payout using a SalaryPayOut class, you don't want engineers to see how you're calculating their salary, so you would wrap the EngineerSalary class with the SalaryPayOut class.
If you're using extension methods defined in naemspaces, Visual Studio will often have a ______ to the left of the line with an error due to ... and will incorporate a ....
lightbulb , not having a namespace , "using" statement with the appropriate namespace at the top of the project
The _________ you use for your static class defines the scope of your extension methods
namespace
Extension methods belong to a _________. To use an extension method, the _________ needs to be defined in scope
namespace, namespace
You can't use extension methods to add ...
new fields to record additional data
You cannot access ___ or ____ ____ using extension methods because
private , protected members , your sponsor class is in a different hierarchy
Extension methods only have access to _________ of a target class because ...
public members , extension methods are defined in an external class
Engineers tend to overdo extension methods by
refactoring everything that could be made into an extension method
If you find a good candidate for an extension methods, make sure you're _______ , and select the most _____ type in the hierarchy to extend
restrictive , specific
Narrow the
scope
Structure your extensions into ___ ___ so that users can (3 things)
separate assemblies , 1. reference just the extensions they need 2. group them logically 3. minimize dependency graph
It makes sense to isolate an extension method assembly when...
several components of an application need the same type of logic
Many organizations have extension methods scattered across projects. Some organizations go to the next stage and put those extension methods into ___ ____ . These are often ...
shared libraries, project-specific libraries
When using autofill in Visual Studio, you can distinguish the regular methods from extension methods in the menu by the icon with a
small down arrow
To create extension methods, you first need to create a _____ with the same name as the namespace you want to create.
solution
To use an extension method, you start by using a static class with a special syntax called a _________ . You then use a ______ to identify the target class or interface you're extending with this new method.
sponsor class , "this statement"
Inside your extension method, you can only use ...
the accessible members of the type you're extending
In your sponsor class, the first argument of the method specifies
the type you're going to extend using the "this" keyword. ex. public static bool MyExtension(this IConfiguration config) { }
If there's a conflict with method signatures, methods declared on _____ take precedence over _________ ____
types , extension methods ex. I created an IsLoaded() method extending Iconfiguration. If Microsoft releases their own method called IsLoaded() on the original type in their library, making it have the same signature, their method will take precedence and hide my extension method.
Your extension method library should make it easy for any developer in your organization to...
use your best practices. So much so, that it would be harder not to follow them.
Shadowing
when an extension method is hidden by a class method that has the same signature, creating unexpected results
Can you use extension methods inside other extension methods?
yes
Only write extension methods that
you know will be used by multiple other classes
General rule for dependencies is...
you want the least amount of unneeded dependencies as possible.