views:

429

answers:

3

I know this could be silly, but would like gurus to clarify it for me... Why is this method defined as static ..

public class MvcApplication : System.Web.HttpApplication
{
    /* Why this method is declared as static? */
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}
+5  A: 

its static because it has no need to be a method directly related to instances of the class, but rather a method that can be used in a static context.

In other words, it only affects the parameter "routes", it doesn't use any class fields or members, so it makes sense it be made static.

Mark
I think, my intention was to understand what's the problem in keep this method as non-static? any performance hits etc.,?
Vadi
@Vadi, There is no problem as such, but if your method does is more like a utility and does not need to handle per-instance states then its better to keep it static. An advantage of static is that you do not need to create an object to call it, which could be ans overhead sometimes. In above case you done need one hence its static. But ofcourse it all depends on the context of the problem, and with such small code snippet noone could actually tell wheter its right to keep it static.
Suraj Chandran
technically, I believe that there are some memory performance issues if you were to make it non-static. Every instance will need a reference to the method, which will impact your memory footprint, but barely. Still, you should keep it static.
Mark
A: 

You only need one routes table and you need the same one used throughout the application. Making it static means you get a global set of values that are defined in a single place.

Peter Marshall
+2  A: 

The method is static because it can be (as Mark points out)... but I think the real reason behind the ASP.NET team making it static (as you're trying to get at with your question of 'why?') was to make unit testing your routes easier.

ASP.NET MVC Pro by Steve Sanderson has a good section (with helper methods) on testing your routes. And I think the MVC Contrib project also has some helper methods for unit testing your routes.

HTHs
Charles

Charlino