m.edmondson
m.edmondson

Reputation: 30862

Explanation of this code

I've just come across the following code which I can't understand:

var dataItem = (SportNode)item.DataItem;
item.FindControl<Literal>("Node", image =>
    image.Text = string.Format("<li data-nodeId='{1}' class='{0}'><a href='/sport?navItems={3}'>{2}</a></li>", "top",
    dataItem.NodeId, dataItem.Text, dataItem.NodeId));

In particular, where does image come from? It's not declared anywhere yet seems to have a type. I certainly can't see it in any parent classes.

Upvotes: 1

Views: 144

Answers (3)

Geoff Huston
Geoff Huston

Reputation: 363

Image, here, is the parameter to an anonymous function - it derives its type from the signature of whatever you are passing it in to; for instance:

    private void PrintResult(Func<Int32, Int32> f)
    {
        Debug.WriteLine(f.Invoke(1));
    }

    //In some other method
    PrintResult(n => n + 2); //prints 3

You can look up more about this if you'd like - I'd search for "Lambda expression" or "anonymous function."

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

This is an anonymous method. image is the name of the parameter to this method. The type of image is inferred from the second parameter of FindControl.

Upvotes: 1

Rick Liddle
Rick Liddle

Reputation: 2714

"image" is the input parameter to the lambda expression.

Read more on lambdas here.

For a more readable and in-depth look at lambdas, Scott Guthrie has a great post introducing them.

Upvotes: 4

Related Questions