Search code examples
c#lambdaanonymous-methods

Please guide me in getting the following line c# lambda expression code


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


Solution

  • 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