Can you add extension methods that you call static methods?

According to Microsoft, "extension methods are a special type of static method, but they are invoked as if they were instance methods of an extended type."

Is there a way to add an extension method, which he called, as if it were a static method? Or do something else that has the same effect?

Edit: By this I mean "called as a static method in an extended class." Sorry for the ambiguity.

+4
source share
2 answers

According to Microsoft, "extension methods are a special type of static method, but they are invoked as if they were instance methods of an extended type."

Yes, extension methods are static methods. All of them can be called in the usual way as static methods, such as extension instance methods for the type that they "extend", and they can even be called extension methods for null reference.

For instance:

public static class Extensions { public static bool IsNullOrEmpty(this string theString) { return string.IsNullOrEmpty(theString); } } // Code elsewhere. string test = null; Console.WriteLine(test.IsNullOrEmpty()); // Valid code. Console.WriteLine(Extensions.IsNullOrEmpty(test)); // Valid code. 

Edit:

Is there a way to add an extension method that it called, as if it were a static method?

Do you want you to call e.g. string.MyExtensionMethod ()? In this case, no, there is no way to do this.

+13
source

Extension methods are static methods. You do not have to do anything.

The only thing that distinguishes the extension method from any other static method is that it can be called as if it were an instance method in addition to the usual call as a static method.

+4
source

All Articles