Explicitly using an extension method C# with Example



Explicitly using an extension method C# with Example

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); 
When to call extension methods as static methods 
There are still scenarios where you would need to use an extension method as a static method: 
Resolving conflict with a member method. This can happen if a new version of a library introduces a new 
member method with the same signature. In this case, the member method will be preferred by the 
compiler. 
Resolving conflicts with another extension method with the same signature. This can happen if two libraries 
include similar extension methods and namespaces of both classes with extension methods are used in the 
same file. 
Passing extension method as a method group into delegate parameter. 
Doing your own binding through Reflection. 
Using the extension method in the Immediate window in Visual Studio. 
Using static 
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. 

0 Comment's

Comment Form

Submit Comment