473,396 Members | 1,914 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,396 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 1822
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.