C# Anonymous Object Tip
I was in the middle of writing a URL helper for the default route in MVC, with this signature:
static string Default(this UrlHelper url, string controller, string action, object id)
My initial implementation looked like this:
static string Default(this UrlHelper url, string controller, string action, object id)
{
return url.RouteUrl("default", new { controller = controller,
action = action,
id = id });
}
That's when Resharper chimed in and grayed some things out for me, teaching me a new trick: If you want your anonymous object field names to be the same as the value you're passing in, you don't need the name.
The abbreviated version looks like this:
static string Default(this UrlHelper url, string controller, string action, object id)
{
return url.RouteUrl("default", new { controller, action, id });
}
Slick! I often do something similar all the time in action methods where I want to redirect but pass along the id. Sounds like I can do this now:
return RedirectToAction("Foo", new {id});
DRY Baby!!!
Posted by: Haacked | October 15, 2008 at 14:29
Very nice, didn't realize you could leave off the names like that.
Chris
Posted by: Chris sutton | October 15, 2008 at 14:40
Cash back!
Posted by: Chris Hardy | October 15, 2008 at 15:00
Argh. If only it'd capitalize them for me, I'd be so happy. But, still a nice tip to save some typing.
Posted by: Mark Brackett | October 20, 2008 at 06:51
How I should write the method that it can take that parameter?
Posted by: Andrey | October 22, 2008 at 01:47
This can be used in LINQ as well
Posted by: Robert | October 22, 2008 at 20:16
Yeah! Same thing happened to me a few days ago.
At first I had an urge to be explicit and keep the name, but I just let it go.
Posted by: Louis DeJardin | October 29, 2008 at 08:20