Joshua Enfield
Joshua Enfield

Reputation: 18308

Extension method - having to use this keyword?

I have added an extension method to the ASP.NET System.Web.UI.Page. Every page in my application inherits from this class.

I cannot just access the extension method, however. I must type this.MyMethod(); instead of just being able to use MyMethod(). I thought that methods/attributes of this were inherently in the default scope. What am I not understanding? Or is this a nuance of extension methods?

Upvotes: 1

Views: 713

Answers (3)

Dan Tao
Dan Tao

Reputation: 128417

I thought that methods/attributes of this were inherently in the default scope.

They are. But extension methods are not methods of this in the default scope; they are static methods accessible via syntactic sugar provided as a courtesy by the compiler.

I believe you already know this, but just to clarify: if ExtensionMethod is an extension method of the class whose scope you're currently in, typing this:

this.ExtensionMethod();

...is the same as:

SomeStaticClass.ExtensionMethod(this);

this needs to be passed as a parameter to ExtensionMethod. The first way above, the compiler simply does this for you.

Naturally, they could have implemented things differently so that the compiler "brings in" extension methods as well as class members into the default scope; they just simply chose not to. Personally, I like that; but I guess it's a subjective matter. Anyway, if you dislike having to type this, it's only a small annoyance, right?

Upvotes: 5

Jeffrey L Whitledge
Jeffrey L Whitledge

Reputation: 59533

is this a nuance of extension methods?

Yes, it is. (As others have explained.)

If you want to use the method without any qualification, then you could just make a class that inherits from Page and includes your method (minus the first paramater, of course). Then make each page in your application inherit from your new custom page.

Upvotes: 2

Alex Zhevzhik
Alex Zhevzhik

Reputation: 3407

In order to use extension method you should declare:

using Namespace.Where.Extension.Method.Is.Located

And don't forget that class that holds extension method should be static.

Upvotes: 0

Related Questions