Question about lambda function

Started by
1 comment, last by SeanMiddleditch 8 years, 3 months ago

In my C# unity5 code I got this

CityButton cb = go.AddComponent<CityButton>();

b.onClick.AddListener (() => {cb.CheckShouldExpand(b);});

my question is

why this part works "() => {cb.CheckShouldExpand(b);}"

but this "(cb, b) => cb.CheckShouldExpand(b);" OR "(b) => cb.CheckShouldExpand(b);" does not ?

because what I understand from the internet MSDN and dotnetperls.com says

() : input parameters

=> goesto

cb.CheckShouldExpand(b) : expression

which means from my understanding the expression part(Right) cb and b doesn't know what it is until you pass it in from the input parameters(Left).

Advertisement

What you might be asking about is how "b" and "cb" are working in the lambda. This is called "capturing", the city button and "b" variables are captured when the lambda is created, and are available when the lambda is executed later.

See Variable Scope in Lambda Expressions.

And also just to clarify,


but this "(cb, b) => cb.CheckShouldExpand(b);" OR "(b) => cb.CheckShouldExpand(b);" does not ?

Those don't work because the delegate must be a nullary function (not take any parameters) so you can bind neither unary nor binary lambdas; the event doesn't know what to pass in as the parameters even if you could bind such a delegate.

Sean Middleditch – Game Systems Engineer – Join my team!

This topic is closed to new replies.

Advertisement