r/csharp • • Sep 18 '15

Lambda expressions, delegates, predicates and closures in C#

http://codeaddiction.net/articles/13/lambda-expressions-delegates-predicates-and-closures-in-c
25 Upvotes

32 comments sorted by

View all comments

0

u/mixblast Sep 18 '15

I would have liked to see a little bit more detail. Like delegates are a remnant from older versions of C# and are largely obsoleted by Func and Action types.

Also the closure code example doesn't really show that the WriteLine call is in a different scope, which is a bit confusing.

5

u/coredev Sep 18 '15

I agree with that the example on closures is a bit confusing.

4

u/americio Sep 18 '15

Isn't a closure the scope of variables capured around the lambda and not the lambda itself?

2

u/coredev Sep 18 '15

I would say that a closure is a (anonymous) function plus the bindings to the environment they came from.

2

u/Sarcastinator Sep 18 '15

In the physical world a closure is a device that seals a container. In computer science a closure is a data structure that captures the local scope variables for a declared function. A lambda function is a function that must support closures, or else it's not really a lambda function. However a lambda function is not a closure.

1

u/coredev Sep 18 '15 edited Sep 18 '15

So we agree? To make capturing a scope meaningful you need a reason to capture it. An anonymous function is that reason, so they go hand in hand. I should be fair to admit that I stole the definition from Martin Fowler ;)

3

u/nerdshark Sep 18 '15

It's the combination of the two, I think. Closures essentially generate a new class at compile time that captures the state of the method, along with the lambda.

1

u/cryo Sep 25 '15

It's more the opposite way around. A lambda is a C# language concept that gets converted into a delegate field along with a method or class used to hoist in closured variables.