« Breaking Changes in xUnit.net 1.1 | Main | xUnit.net 1.1 Released »

October 15, 2008

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 });
}

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00e54fbd8c4988340105358d956a970c

Listed below are links to weblogs that reference C# Anonymous Object Tip:

Comments

Feed You can follow this conversation by subscribing to the comment feed for this post.

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!!!

Very nice, didn't realize you could leave off the names like that.

Chris

Cash back!

Argh. If only it'd capitalize them for me, I'd be so happy. But, still a nice tip to save some typing.

How I should write the method that it can take that parameter?

This can be used in LINQ as well

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.

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment