views:

142

answers:

2

Hello,

would someone please write this code:

this.Loaded += (s, e) => this.loaded = true;

into several code lines so I can retrace the meaning?

In my code sample there is no s or e ?

A: 

It's a shorthand for an event handler. s is what you normally see as object sender and e is some type of EventArgs. Basically it could be written like this:

public void MyHandler(object sender, EventArgs e)
{
   this.loaded = true;
}

and the calling code would be something like:

this.Loaded += MyHandler;
klausbyskov
+4  A: 

This may make it slightly clearer, just by renaming:

this.Loaded += (sender, args) => this.loaded = true;

Or by giving them types:

this.Loaded += (object sender, EventArgs args) => this.loaded = true;

They're the parameters for the delegate. Here's the equivalent in C# 2:

this.Loaded += delegate (object sender, EventArgs args) { this.loaded = true; };

Does that help?

Here's the equivalent in C# 1 (fortunately there are no captured variables, which makes life a bit easier...)

this.Loaded += new EventHandler(SetLoadedToTrue);

...

private void SetLoadedToTrue(object sender, EventArgs args)
{
    this.loaded = true;
}

(That's all assuming the Loaded event is of type EventHandler; if it's not, the signature would be different in the obvious way.)

Jon Skeet
Give me a chance :-))
Obalix
Ahhh, mr. Skeet, why do I even bother answering C# questions when you are online ;-)
klausbyskov
(Was in the middle of typing almost exactly this into an answer, but Jon Skeet > me) To address the original question: just like how the names of the parameters to SetLoadedToTrue ("sender" and "args") are themselves variable declarations that don't appear elsewhere in the call site's code, the "s" and "e" in the lambda declaration are likewise declared for the scope of the lambda.
Tanzelax
thank you Jon answer is clear.
msfanboy