For those who haven’t been keeping score of what’s new in the upcoming C# 4.0 release, one of the features that people are quite chuffed about is named parameters. They essentially let you call a method by naming the parameters for which you would like to specify a value, and the ones you omit get a default value. It looks kind of like this:

DoStuff(foo: "hello", bar: "world", answer: 42);

Thinking about named parameters has me wondering: One of the tricks people have started using in C# 3.0 is to make use of anonymous types to provide a sort of “dynamic parameters” feature. I do it in my AddInputParameters extension method, and the ASP.NET MVC team do it to define routes. This example taken from Phil Haack’s blog:

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });

 

See that third parameter? It’s an anonymous type that the MapRoute method can parse into a sort of map (“controller” maps to “Home”, “action” maps to “Index” etc).

What would be nice is if we could use the named parameters syntax to call methods like this. We could effectively omit the “new {}” part of the call:

routes.MapRoute("Default", "{controller}/{action}/{id}", controller: "Home", action: "Index", id: "");

I don’t know how such a method would be declared, but the syntax reminds me of the “params” keyword, where you can tell your method that the last parameter is an array of unknown length and can be passed as arbitrary parameters. So perhaps something like:

void MapRoute(string name, string path, params IDictionary<string, object> maps);

So now that last parameter would seamlessly pass our named parameter list into the “maps” dictionary.

What do you think? Anything that removes a bit of extra punctuation from the code would have to be helpful.