4

Can someone give me a an eloquent, in depth explaination of why is this ok:

EventHandler e;

private void foobar(){
     e = new EventHandler((o, s) => {
           somectl.LayoutUpdated -= e;
     }
     somectl.LayoutUpdated += e;
}

But this is not:

private void foobar(){
     EventHandler e = new EventHandler((o, s) => {
           somectl.LayoutUpdated -= e;
     }
     somectl.LayoutUpdated += e;
}

Nor is this:

private void foobar(){
    EventHandler e;
    e = new EventHandler((o, s) => {
          somectl.LayoutUpdated -= e;
    }
    somectl.LayoutUpdated += e;
}
1

3 Answers 3

2

This has less to do with the lambdas than you might think. For example, this would fail:

int i = i + 1;

As would this:

int i;
if (condition) {i = 0;}
i = i + 1;

Or:

int i;
if (condition) {Console.WriteLine(i);}
i = 1;

The lambda expressions fail for the same reasons: the middle one because you can't refer to any variable within its declaration, and the last because you can't guarantee that e will have been initialized before you attempt to use it within the lambda.

The first example works fine because fields are always initialized. They will either be given a value in the class's constructor, or they will be set to their default automatically. If you wanted to make this work within the scope of the method, you just need to assign your variable when you declare it.

private void foobar(){
    EventHandler e = null;
    e = new EventHandler((o, s) => {
          somectl.LayoutUpdated -= e;
    }
    somectl.LayoutUpdated += e;
}
Sign up to request clarification or add additional context in comments.

Comments

2

The last two won't compile because you can't reference e before you finish assigning it.

The first one works since this restriction does not apply to fields.

You can make the last one work by assigning it to null first so that it will be definitely assigned.

EventHandler e = null;
e = (o, s) => {
      somectl.LayoutUpdated -= e;
};
somectl.LayoutUpdated += e;

Comments

0

In the last 2 cases, the compiler can check that you're working with an unassigned local variable inside the lambda. In the first case, because of the global variable, the compiler can't check this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.