Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make an Extension Method Static/Shared?

OK, I've probably misunderstood something here but, as far as I can see ...

  • An extension method has to be contained in a module, not a class
  • You can't make methods in modules Static/Shared
  • Therefore you can't use an extension method on a class without instantiating it.

In other words you can't make an extension method on String called "MyExtensionMethod" and use:

String.MyExtensionMethod("String")

But instead ..

Dim test As String
test.MyExtensionMethod("string")

Is this correct? Or is there a way I can get extension methods to work as static methods?

like image 296
Bob Tway Avatar asked May 21 '10 09:05

Bob Tway


People also ask

Can extension methods be static?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

Why do extension methods need to be in a static class?

It is compulsion that the Extension method must be in a Static class only so that only one Instance is created. For example, if you place the following in ASP.Net page it will not work. Though error will not come, but you will not see the method available. The above will not work.

Do extension methods have access to private members?

Extension methods can also access private static members of their static utility class. Even though this is tagged as C#, this applies to any of the . NET languages which provide support for extension methods.


1 Answers

You are correct. Extension methods can only act on instances of a type.

And no, unfortunately there's no crafty way to write extension methods that act on the types themselves, behaving like static methods.

like image 141
LukeH Avatar answered Nov 07 '22 01:11

LukeH