Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you add extension methods that you call like static methods? [duplicate]

According to Microsoft, "Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type".

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

Edit: By which I mean "called as if it was a static method on the extended class". Sorry for the ambiguity.

like image 870
Spike Avatar asked Dec 04 '22 11:12

Spike


2 Answers

According to Microsoft, "Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type".

Yes, extension methods are static methods. They can all be called in the normal way as static methods, as extension instance methods on the type they "extend", and they can even be called as extension methods on a null reference.

For example:

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 was a static method?

Do you mean you want to call, for example, string.MyExtensionMethod()? In this case, no, there is no way to do that.

like image 88
Rich Avatar answered Mar 01 '23 23:03

Rich


Extension methods are static methods. You don't need to do anything.

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

like image 42
Jörg W Mittag Avatar answered Mar 01 '23 22:03

Jörg W Mittag