Why doesn't this anonymous method work during lambda?

I am learning about anonymous methods, lambdas, etc. and can't find the reason why it doesn't work here:

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

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

      

+3


source to share


2 answers


You forgot the return

result of the instruction:

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

      

Think of it delegate

as a complete method that should be as independent as possible for the independent method, apart from the naming part. So, you can think of 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 doesn't the second one work? Think about it to better understand what's going on. It just simplifies the picture:

The first lambda is the: operator w.Length == 5

, and the operator has a result that actually returns it. Is not it?

But the second: { w.Length == 5 }

is a block. And the block doesn't return anything, except that you explicitly do it.

+11


source


You have to put the statement return

in the delegate body, for example:

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

      



You can think of what the return

arrow would mean in the lambda version, so it works.

+1


source







All Articles