0

If I want to declare my action method static, can I have it? If yes then How to do it and what is the use of it? If there is no use as then why MVC allow it to define? For e.g.

public static ActionResult Index()
{
  //Is it possible?
   return View();
}

If this is possible can someone tell me an example for extension method?

Imgane5h
  • 304
  • 1
  • 3
  • 16
  • 1
    What would be the reasoning behind it? – walther Nov 03 '15 at 10:26
  • I have added another query as well... It doesn't answer that so created different question – Imgane5h Nov 03 '15 at 10:27
  • @walther somebody asked me the same question and i was confused so thought of sharing here – Imgane5h Nov 03 '15 at 10:28
  • 1
    `static` actions are not supported (at least not without overriding the `ActionInvoker` and making a big mess). The question is: why? – haim770 Nov 03 '15 at 10:29
  • http://www.asp.net/mvc/overview/getting-started/lifecycle-of-an-aspnet-mvc-5-application – haim770 Nov 03 '15 at 10:29
  • @CodeCaster the duplicate question you are pointing to has answer voted most says you can have static method returning ActionResult but compiler gives error when i do that....so i think that's not useful and why people voted it i dont know? – Imgane5h Nov 03 '15 at 10:49
  • @Ganesh the answer pretty clearly states _"you can declare it static, of course, **but it will not be called**"_. The static method will generate a compiler error on non-static member access, such as the `View()` method. You seem to lack fundamental C# knowledge. MVC is just a library that you can use with C#. MVC does not change the C# rules. – CodeCaster Nov 03 '15 at 10:52

1 Answers1

3

MVC doesn't allow to define it, C# does. Just because some construct is possible in the programming language, doesn't mean that your framework will support it. There are many other things that are possible to write in C#, but which MVC will ignore or complain about.

So, no, no static actions. No extension methods either. Extension methods are just a syntax sugar; a sleight of hand by the C# compiler. When the code gets compiled, the extension methods become no different than any other static methods. Calls to them are converted to simple static method calls. In other words, even if you write this:

myObject.extensionMethod(42);

It will get compiled to this:

ExtensionClass.extensionMethod(myObject, 42);

So by the time your application is run and MVC framework kicks in, all information about any extension methods is lost. MVC couldn't support "extension method actions" even if it wanted to, because it couldn't figure out which extension methods apply to which controller class.

Vilx-
  • 104,512
  • 87
  • 279
  • 422