3
<%= MyClass.GetData(() => new[] { Html.TextBox(prefix + "Postcode", Customer.ZipCode, new { maxlength = 7 }), Html.ValidationIcon(prefix + "ZipCode") })%>

Can someone please explain me what the MyClass.GetData method is getting passed as parameter?

I don't expect a full explanation and i know that i should learn further into anonyous methods and lamda expression... But for now can you explain what the the code as from "() =>......." means?

And if you know some nice articles that builds towards understanding material like this that would be cool !

HerbalMart
  • 1,669
  • 3
  • 27
  • 50

3 Answers3

5

The () => new [] { ... } is a lambda expression which is short-hand syntax for an anonymous delegate. This means that you are passing in essentially the equivalent of a pointer to a function that takes no arguments, the () part indicates the arguments, and returns the results in { } braces (Html.TextBox.... etc).

Essentially, this would be equivalent to passing a method name that accomplishes the same thing, but it's more concise syntax:

MyClass.GetData(() => new[] { Html.TextBox(prefix + "Postcode", Customer.ZipCode, new { maxlength = 7 }), Html.ValidationIcon(prefix + "ZipCode") }

is the same, roughly, as creating a method, then passing that method name in.

private WebControl[] GetControls()
{
    return new[] { Html.TextBox(prefix + "Postcode", Customer.ZipCode, new { maxlength = 7 }), Html.ValidationIcon(prefix + "ZipCode");
}

....

MyClass.GetData(GetControls);

p.s. Here's a good basic lambda tutorial: http://blogs.msdn.com/b/ericwhite/archive/2006/10/03/lambda-expressions.aspx

James Michael Hare
  • 37,767
  • 9
  • 73
  • 83
2

() => means an lambda that does not take any parameters. So you are passing into GetData a lambda that takes no parameters and returns a new array.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
2

It means: Here is an anonymous delegate that takes no argument and returns an array of objects whose type will be inferred from the return values of Html.TextBox() and Html.ValidationIcon().

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479