Extensions Methods - mcbride-clint/DeveloperCurriculum GitHub Wiki
Extension Methods in C# provide a way to add functionality to types without modifying the original type.
The methods that are created closely resemble existing methods through the instance.ExtensionMethod()
syntax.
They can be applied to any Type including Interfaces.
They appear to be native functionality when used but in reality they are just special static methods that make discovering added functionality easier.
The this
keyword before the first parameter tells the compiler to add the method to all instances of that parameter's type.
This extension method example adds a new method to all strings.
namespace Examples
public static class StringExtensions {
public static bool HasValue(this string inputString){
return !string.IsNullOrWhitespace(inputstring);
}
}
}
Other code files can take advantage of this method by adding a using Examples.StringExtensions
to the top of their file.
using Examples.StringExtensions;
...
// String Literal
if ("Hello World".HasValue()) { ... }
// String Variable
string thingy = "Hello World";
if (thingy.HasValue()) { ... }
// String Property
if (user.FirstName.HasValue()) { ... }
Since the methods are just special static methods, they can still be used as normal static methods as well.
string thingy = "Hello World";
// No Using Statement
Examples.StringExtensions.HasValue(thingy);
// Using Statement
HasValue(thingy);
Using with Interfaces
Extensions can be very powerful when used with Interfaces. When an extension is added to an Interface then every class that implements that Interface will gain that Extension without each having to implement the method themselves.
A Microsoft example of this is LINQ.
It is a collection of IEnumerable<T>
Extension methods that add a large amount of functionality to any implemented type, such as List.
See Also
- Microsoft Docs - Extension Methods - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
- Pluralsight Course - C# Extension Methods - https://app.pluralsight.com/library/courses/c-sharp-extension-methods/table-of-contents