Tomas
Tomas

Reputation: 18107

Controller extension method without this

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

public ActionResult Foo()
{
    this.ExtensionMethod();
    return View();
}

public static void ExtensionMethod(this Controller controller)
{

}

What I don't like is that ExtensionMethod must be called with this keyword. Is it possible to get rid of this?

Upvotes: 6

Views: 5232

Answers (3)

Richard Friend
Richard Friend

Reputation: 16018

You can use it like.

this.ExtensionMethod();

or

ExtenstionClassName.ExtensionMethod(this);

Your choice...

Upvotes: 2

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

That's how it is. You can't do anything against it.

You may think about putting it into a base class - which is mostly not a great idea (because it blows up the base class).

Upvotes: 3

shovavnik
shovavnik

Reputation: 2927

No.

It is the this keyword that makes the method an extension method. Without it, it's just a static method.

Edit: Sorry, I misread the question. There are two this keywords: one in the extension method, and one used to call it.

The reason you need the this keyword when you call it is that you need to specify the object that is being extended. C# doesn't automatically resolve local method calls to extension methods unless you specify the this keyword.

Upvotes: 11

Related Questions