Anymous method and outer variables

G

Guest

Hi,
In the .NET 2.0 Beta 2 documentation, the following is wrtten about
anonymous methods:
Unlike local variables, the lifetime of the outer variable extends until the
delegates that reference the anonymous methods are eligible to garbage
collection. The value of n is captured at the time the delegate is created.

The example shows an int that is used in the anonymous method block. That
int then becomes an outer variable it's value is captured at the creation of
the anonymous code block.

That's good with value type. But what about reference type? How is the value
"captured"?

Let's change the example.
int n = 0;
MyDel d = new MyDel() { Console.WriteLine("Copy #:{0}", ++n); };
To
MyClass n = new MyClass();
MyDel d = new MyDel() { Console.WriteLine("Copy #:{0}", n.SomeProperty); };

How is the value of n captured since it's a reference type? Will it compiles
at all?

Etienne Fortin
 
R

Richard Blewett [DevelopMentor]

Etienne Fortin said:
Hi,
In the .NET 2.0 Beta 2 documentation, the following is wrtten about
anonymous methods:
Unlike local variables, the lifetime of the outer variable extends until
the
delegates that reference the anonymous methods are eligible to garbage
collection. The value of n is captured at the time the delegate is
created.

The example shows an int that is used in the anonymous method block. That
int then becomes an outer variable it's value is captured at the creation
of
the anonymous code block.

That's good with value type. But what about reference type? How is the
value
"captured"?

Let's change the example.
int n = 0;
MyDel d = new MyDel() { Console.WriteLine("Copy #:{0}", ++n); };
To
MyClass n = new MyClass();
MyDel d = new MyDel() { Console.WriteLine("Copy #:{0}",
n.SomeProperty); };

How is the value of n captured since it's a reference type? Will it
compiles
at all?

Etienne Fortin

The "local" variables you reference in the anonymous code block actually
become instance members on a compiler generated class (that also contains
the anonymous method) so it works just like any other member variable. This
means that things you regard as local variables, maybe on the stack, are
potentially being accessed by a hidden reference and are allocated on the
managed heap.

The other effect of this is that if you modify an outer variable in the
anonymous method the code outside of the anonymous method can see the
change - which has implications for thread synchronization

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
 

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