"Anonymous methods" and "closures"

P

Peter

Hi

I've been delving into "delegates" and "anonymous methods", and now
I've come across the term "closure".

Some information I've found says that C# does not have closures, other
information says that C# does have closures.

My problem is I can't quite grasp what "closures" are. The examples I
have seen seem to be "anonymous methods". What is the subtle difference
between a closure and an anonymous method?

Thanks,
Peter
 
P

Peter

Nicholas said:
Anonymous methods are closures. It's the fact that they can access
variables outside it's scope that makes it a closure:

http://en.wikipedia.org/wiki/Closure_(computer_science)

Thanks for the link. I've read through it once, but I'll need to read
it a few times.

Are you saying that all anonymous methods in C# are also closures - or
just that anonymous methods which access outside variables can be
termed closures? And anonymous methods which don't access outside
variables are not closures (simply "anonymous methods").

If "anonymous method" is just a synonym for "closure" then fine - but
it sure confuses things when you're trying to get to grips with these
concepts.

Thanks,
Peter
 
P

Peter Morris

Think of it this way. Might not be right, but it works for me :)

public delegate void MyDelegate();

public class MyClass
{
public void TwoExamples()
{
//Delegate to a method
MyDelegate x = DoSomething;

//Anonymous method enclosed in another method
//A closure.
MyDelegate y = delegate()
{
//A closure can access local variables
//of it's containing method
x = null;
};
}

public void DoSomething()
{
//Here we have no concept of the local variable "x"
}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top