Extension methods can also be used like ordinary static class methods. This way of calling an extension method is more verbose, but is necessary in some cases.
static class StringExtensions
{
public static string Shorten(this string text, int length)
{
return text.Substring(0, length);
}
}
Usage:
var newString = StringExtensions.Shorten("Hello World", 5);
There are still scenarios where you would need to use an extension method as a static method:
Reflection
.If a using static
directive is used to bring static members of a static class into global scope, extension methods are skipped. Example:
using static OurNamespace.StringExtensions; // refers to class in previous example
// OK: extension method syntax still works.
"Hello World".Shorten(5);
// OK: static method syntax still works.
OurNamespace.StringExtensions.Shorten("Hello World", 5);
// Compile time error: extension methods can't be called as static without specifying class.
Shorten("Hello World", 5);
If you remove the this
modifier from the first argument of the Shorten
method, the last line will compile.