Why this anonymous method does not work while the lambda does?

170 views Asked by At

I am learning anonymous methods, lambdas etc. and cannot find the reason why it does not work here:

// this does not work
MyDictionary.Keys.Where(delegate(string s) { s.Length == 5; });

// this works
MyDictionary.Keys.Where(w => w.Length == 5);
2

There are 2 answers

5
amiry jd On BEST ANSWER

You forgot to return the result of statement:

MyDictionary.Keys.Where(delegate(string s) { return s.Length == 5; });

Think about delegate as a complete method which have to be as same as possible to an independent method, except the naming part. So, you can imagine it as:

delegate(string s) {
    // you would need to return something here:
    return s.Length == 5; 
}

UPDATE:

Also, think about these 2 lambdas:

MyDictionary.Keys.Where(w => w.Length == 5); // works
MyDictionary.Keys.Where(w => { w.Length == 5 }); // does not work

Why the second one is not working? Think this way to getting a better vision of what's happening. It's just about simplifying the picture:

The first lambda is a statement: w.Length == 5 and a statement has a result which returns it actually. Doesn't?

But the second one: { w.Length == 5 } is a block. And a block does not return anything, except you explicitly do it.

1
rems4e On

You have to put a return statement in the body of the delegate, like this:

MyDictionary.Keys.Where(delegate(string s) { return s.Length == 5; });

You can thing as the return being kind of implied by the arrow in the lambda version, that's why it is working.