Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
Tomas Avatar asked Aug 24 '12 08:08

Tomas


People also ask

What parameter does an extend () method requires?

Parameters of extend() function in Python The list extend() method has only one parameter, and that is an iterable. The iterable can be a list, tuple (it is like an immutable list), string, set or, even a dictionary.

Can we override extension method?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.

Do extension methods have to be static?

An extension method must be a static method. An extension method must be inside a static class -- the class can have any name. The parameter in an extension method should always have the "this" keyword preceding the type on which the method needs to be called.

How do you write an extension method?

To define and call the extension method Define a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.


1 Answers

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.

like image 81
shovavnik Avatar answered Sep 29 '22 20:09

shovavnik