Question

I'm wondering about something. Let's say I have an event named SomethingChanged with 2 parameters. first is the sender which fires the event. second one is just a number.

Case 1:

I defined this event in SenderClass:

public event Action<SenderClass, int> SomethingChanged;

Normally I can attach the event handler like this:

item.SomethingChanged += (sender, p) =>
{
    if (p == 1) sender.F1();
    else sender.F2();
};

Case 2:

But if I remove the sender parameter:

public event Action<int> SomethingChanged;

it does not change a thing and I still can use it:

item.SomethingChanged += p =>
{
    if (p == 1) item.F1();
    else item.F2();
};

It's obvious to me that by removing sender the following usage is no longer feasible:

item.SomethingChanged += item_SomethingChanged;

private void item_SomethingChanged(SenderClass sender, int p)
{
    if (p == 1) sender.F1();
    else sender.F2();
}

Question:

But the thing I'm curious about is How the compiler finds about that sender in Case2? Does it use reflection or do they both translate into the same assembly code? Or?

Était-ce utile?

La solution

That's because in your second case, you are using the item local variable, which is accessible from your lambda. The compiler doesn't need to find out about a sender variable because it is simply not being used - nor it is being provided, it simply does not exist at all in your second case.

From Variable Scope in Lambda Expressions:

Lambdas can refer to outer variables that are in scope in the enclosing method or type in which the lambda is defined. Variables that are captured in this manner are stored for use in the lambda expression even if variables would otherwise go out of scope and be garbage collected. An outer variable must be definitely assigned before it can be consumed in a lambda expression.

If you want to get an idea of how variable capturing happens, check the answer from the link provided by @Sriram in the comments.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top