0

I'm doing a tutorial on MVC 3 and I stumbled upon the helper @Html.ActionLink(genre.Name, "Browse", new {genre = genre.Name}).

Now I understand what the values do and that the third value is a route parameter value but this is the first time I'm seeing this kind of syntax which is really bugging me for some reason.

What I mean exactly is new {genre = genre.Name}. I've come to understand that "new" precedes object/type declaration, however, this time it's simply the "new" keyword and the curly brackets. How exactly is this processed?

2
  • i am thinking more of instantiating the object 'genre' as var genre = new genre.Name; but i may be wrong !! Commented Nov 27, 2012 at 22:33
  • @Andrew If any of the replies satisfies you please mark it as answer. Do that for your old questions as well. Commented Nov 28, 2012 at 14:57

3 Answers 3

2

The syntax new { prop = val } creates an anonymous type. It's essentially the same as creating an instance of a class, except you're declaring the class and the instance all in one shot. Some people think that anonymous types are not statically typed or are not type safe. This isn't true. The types of the properties are inferred from the values they are assigned. This construction is used frequently in MVC and in linq.

Note that this syntax is not specific to MVC. You can use it anywhere it's convenient. I make a fair amount of use of anonymous types in day-to-day coding.

Sign up to request clarification or add additional context in comments.

Comments

1

It's simple.. the first parameter is the link you want to display, so genre.Name can corresponds to Rock. The second argument is the action, the third argument your Controller class. The last parameter is the route values in the form of an anonymous object (an object you will never use again, the MVC engine uses the anonymous object in this case). So your action(method) takes a string argument.

For example: "Home" is the link the user sees (the first argument), Home (the second argument) is the action (method) to your Controller class, and it takes a string argument.

class HomeController
{
  public ActionResult GenreAction(string genre)
  {

  }
}

When a request is made, it becomes Home/GenreAction/genre

Comments

0

It's a C# language feature called Anonymous Type, introduced with C# 3.5 if I'm not mistaken.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.