Controller extension method without this

I would like to create a controller extension method. What I got so far below

public ActionResult Foo() { this.ExtensionMethod(); return View(); } public static void ExtensionMethod(this Controller controller) { } 

I don't like that ExtensionMethod should be called with the this . Is it possible to get rid of this ?

+4
source share
3 answers

No.

This is the this , which makes the method an extension method. Without it, this is just a static method.

Edit: Sorry, I misunderstood the question. There are two this words: one in the extension method, and one of them is used to call it.

The reason you need the this keyword when you call it is because you need to specify an object that is expanding. C # does not automatically allow local method calls to extension methods unless you specify the this .

+8
source

That's how it is. You cannot do anything against it.

You might consider putting it in a base class, which is basically not a great idea (because it explodes the base class).

+3
source

You can use it as.

 this.ExtensionMethod(); 

or

 ExtenstionClassName.ExtensionMethod(this); 

Your choice...

+2
source

All Articles