473,327 Members | 1,936 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

Anonymous methods

Hello!

Here I have some text from a book I read. It says:
"An interesting point to note concerning anonymous methods is that they are
effectively local to the code
block that contains them, and they have access to local variables in this
scope. If you use such a variable
it becomes an outer variable. Outer variables are not disposed of when they
go out of scope like other
local variables are; instead, they live on until the anonymous method that
use them are destroyed.
This may be some time later than you expect and is definately something to
bed careful about."

I have one questions about the above text.
What does this mean in the text: "If you use such a variable
it becomes an outer variable. Outer variables are not disposed of when they
go out of scope like other
local variables are; instead, they live on until the anonymous method that
use them are destroyed.
This may be some time later than you expect and is definately something to
bed careful about."

In main below I have defined an anonymous method. Is it possible that you
can exemplify the
answer by using main below and the anonymous method.

static void Main(string[] args)
{
Connection myConnection1 = new Connection();
myConnection1.Name = "First connection.";

myConnection1.MessageArrived += delegate(object source, EventArgs e)
{
Console.WriteLine("Message arrived from: {0}",
((Connection)source).Name);
Console.WriteLine("Message Text: {0}",
((MessageArrivedEventArgs)e).Message);
};

myConnection1.Connect();
Console.ReadKey();
}

//Tony
Jun 27 '08 #1
2 1816
Tony <jo*****************@telia.comwrote:
Here I have some text from a book I read. It says:
"An interesting point to note concerning anonymous methods is that they are
effectively local to the code
block that contains them, and they have access to local variables in this
scope. If you use such a variable
it becomes an outer variable. Outer variables are not disposed of when they
go out of scope like other
local variables are; instead, they live on until the anonymous method that
use them are destroyed.
This may be some time later than you expect and is definately something to
bed careful about."
The author is being *slightly* sloppy about terminology there, I
believe. In fact, any variable whose scope contains an inner method is
an outer variable. If the variable is *used* within an anonymous method
it becomes a *captured* outer variable (aka captured variable). It's
only captured outer variables whose lifetimes are extended.
I have one questions about the above text.
What does this mean in the text: "If you use such a variable
it becomes an outer variable. Outer variables are not disposed of when they
go out of scope like other
local variables are; instead, they live on until the anonymous method that
use them are destroyed.
This may be some time later than you expect and is definately something to
bed careful about."
Basically, it means the variable is no longer held on the stack.
Instead, it's held in an instance of a class - the anonymous method
holds a reference to an instance of the class, and the stack in the
method holds a reference to an instance too. Things become more
confusing when there are multiple "instances" of the variable due to
loops and things...
In main below I have defined an anonymous method. Is it possible that you
can exemplify the
answer by using main below and the anonymous method.

static void Main(string[] args)
{
Connection myConnection1 = new Connection();
myConnection1.Name = "First connection.";

myConnection1.MessageArrived += delegate(object source, EventArgs e)
{
Console.WriteLine("Message arrived from: {0}",
((Connection)source).Name);
Console.WriteLine("Message Text: {0}",
((MessageArrivedEventArgs)e).Message);
};

myConnection1.Connect();
Console.ReadKey();
}
There are no captured variables there - your anonymous method doesn't
use any of the local variables from the Main method. Here's an example
which does:

static void Main()
{
string text = "Hello!";
ThreadStart starter = delegate { Console.WriteLine(text); }

text = "Surprise!";
new Thread(starter).Start();
}

The "text" variable is captured by the anonymous method. Note that it's
the *variable* which is captured rather than just its initial value,
which is why the "Surprise!" is printed to the console. To learn what's
going on behind the scenes, I suggest you compile the code above and
then look at it carefully in reflector, flicking between the C# and IL
decompilations, and noting the extra class created for you.

Anonymous methods (and lambda expressions) are incredibly useful, but
mechanics are pretty complicated...

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #2
In article <Om**************@TK2MSFTNGP06.phx.gbl>,
Tony <jo*****************@telia.comwrote:
I have one questions about the above text.
What does this mean in the text: "If you use such a variable
it becomes an outer variable. Outer variables are not disposed of when they
go out of scope like other
local variables are; instead, they live on until the anonymous method that
use them are destroyed.
This may be some time later than you expect and is definately something to
bed careful about."
Usually scope lines up with the visual appearance of the code

class c
method m
block f (for for or if)

and when you leave or go "out of" a scope, a variable no longer exists.
Anonymous methods lead to an invisible expansion and thus
*continuation* of the scope of a variable.

If you create an anonymous method that refers to variable that*LOOKS
like it is not local to the anonymous method, then that appearance is
incorrect -- the scope of the variable is the anonymous method.

This has implications for the value that is used in the anonymous
method, as well as for the system (i.e. when an object gets garbage
collected).

--
J.B. Moreno
Jun 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Cordell Lawrence | last post by:
Okay guys, We are wondering if this is a bug in Framework 2.0.40607 and looking for some clarification on the issue. Take a look at the folowing code. public delegate bool BoundryTest(int...
9
by: John Smith | last post by:
I really can not appreciate why Microsoft has introduced Anonymous methods. It promotes quick and dirty style of programming and as I can see it offers no advantages over normal methods. I have...
7
by: Alexandre | last post by:
cross post: Hi can someone justify the use of these anonymous methods in C# 2.0 & 3.0 ? I simply do not see a use for them. can you show me an instance where thay can be useful ?? best...
7
by: d225563 | last post by:
I read an article that had a really elegant solution to pass parameters to a thread by using an anonymous method as your ThreadStart. It seemed pretty slick and even worked when I tried it. ...
7
by: Bill Woodruff | last post by:
I've found it's no problem to insert instances of named delegates as values into a generic dictionary of the form : private Dictionary<KeyType, DelegatemyDictionary = new Dictionary<KeyType,...
22
by: PJ6 | last post by:
I just learned about anonymous methods and was taken aback to discover that they are only available in C#. What, is there still a stigma against VB.Net, that maybe somehow this is a language that...
4
by: Frankie | last post by:
I have just gotten up to speed on what anonymous methods are (syntax, capabilities, etc), and how they can be used with /called via delegates. What I am wondering is... 1. Are they only/mostly...
0
by: Peter Duniho | last post by:
On Mon, 01 Sep 2008 16:14:10 -0700, Blip <blip@krumpli.comwrote: Briefly, an anonymous method is exactly that: a method without a name. When you use the "delegate" keyword to declare an...
4
by: Peter | last post by:
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.