3

I'm trying to learn C# and MVC3. I wanted to have a WebGrid column as an Html.Action link, however, it wouldn't work until I did this:

grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { id = item.Id }))

So I know that this fixes it but why? The (item) looks like a cast but what is the => for? From reading other questions I see that it's evidently bad to do this for some reason - why?

BenGC
  • 2,814
  • 3
  • 23
  • 30

2 Answers2

8

This is known as a lambda expression / anonymous function in C#. The () portion is the argument list and the => indicates the right hand side is the body / expression of the lambda.

Here's a slightly expanded form which may be a bit clearer

Func<ItemType, string> linkFunction = (item) =>
{
  return Html.ActionLink("Edit", "Edit", new { id = item.Id });
};
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
7

That would be a lambda expression. And no, using lambda's is not bad, it's a (very) good thing.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
Claus Jørgensen
  • 25,882
  • 9
  • 87
  • 150
  • @RichK: I upvoted the answer but removed "MSDN is your friend" because it added a condescending tone to an otherwise excellent answer. – Andrew Hare Aug 16 '11 at 20:07
  • Ah, it looks like I may have stomped out Claus's extra sentence there with my original edit. Sorry about that :) – Andrew Hare Aug 16 '11 at 20:09