OK, I've probably misunderstood something here but, as far as I can see ...
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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With