4

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.

Spike
  • 2,016
  • 12
  • 27
  • 1
    No, and there is some discussion at http://stackoverflow.com/questions/638850 – Joe Daley Oct 07 '10 at 01:03
  • @Joe: "no" to what? See the answers below. – Michael Petrotta Oct 07 '10 at 01:04
  • 1
    @Michael: I mean no, C# does not support extension methods that can be called as static methods on the target class. The link discusses why that is not supported. You can call extensions methods statically on the extension class, but I thought he was asking the former. – Joe Daley Oct 07 '10 at 01:08
  • @Joe: Gotcha. Yeah, it can be interpreted either way, but I think you're right as far as the poster's actual question. – Michael Petrotta Oct 07 '10 at 01:28

2 Answers2

13

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.

Rich
  • 3,081
  • 1
  • 22
  • 24
  • Yes, I did mean that. I took, "For client code written in C# there is no apparent difference between calling an extension method and the methods that are actually defined in a type", at face value and didn't think I could call them on null references. – Spike Oct 07 '10 at 02:58
4

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653