473,385 Members | 1,357 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,385 software developers and data experts.

Re: Help with anonymous methods

On Mon, 01 Sep 2008 16:14:10 -0700, Blip <bl**@krumpli.comwrote:
[...]
lblErrorCode.Invoke(new MethodInvoker(delegate { lblErrorCode.Text =
Enum.GetName(typeof(ErrorCodes), Int32.Parse(msg)); }));

This works, but I don't have a clue why. Can someone explain what's
going on here in simple terms? Thanks, Tom
Briefly, an anonymous method is exactly that: a method without a name.

When you use the "delegate" keyword to declare an anonymous method, all
you're doing is writing a method the same as you would anywhere else,
except that it doesn't have a name, and so you have to use it right away
rather than being able to refer to it elsewhere. (And I mean that only in
the static, "we're writing the code now" sense of "right away"...obviously
at run-time, as long as you've created a delegate variable that refers to
the anonymous method, that can be used any time, any place you like).

You can even declare your anonymous method with parameters, by putting
them after the "delegate" keyword. For example, suppose you want to
declare an event handler anonymously. You could do this:

EventHandler handler = delegate(object sender, EventArgs e) { // your
code here };

In the method, you can refer to "sender" and "e" just as you could in a
named method.

And just as a named method has access to members that are in any class
that contains the named method, the anonymous method has access to any
containing member's member. The thing that makes it a little odd is that
whereas a named method is contained only by one or more classes, an
anonymous method can be contained by a named method. This means it _also_
has access to anything in the named method that's in the same scope as the
anonymous method.

That's where the use of the "msg" parameter in your example comes in. The
anonymous method has access to it, because "msg" is in scope in the same
place that the anonymous method is declared.

As far as all that goes, I think it's really pretty simple. As I said,
it's basically the same as declaring any method anywhere.

The one sort of odd part is that when an anonymous method uses a parameter
or local variable like this, it gets "captured". To understand why,
consider that the anonymous method can be executed at any time, not just
while the containing method is still executing. When a method returns,
its parameters and variables no longer exist and so without capturing, an
anonymous method that used them would be in trouble.

C# gets around this by moving any parameters or local variables into a
hidden class accessible by the anonymous method, so that they will stay
alive as long as the anonymous method does.

Now, as if that weren't potentially confusing enough, it's important to
understand that these captured variables are actually created according to
the scope in which they are declared. This:

int i;
List<Actionactions = new List<Action>();

for (i = 0; i < 5; i++)
{
actions.Add(delegate { Console.WriteLine(i); });
}

foreach (Action action in actions)
{
action();
}

Produces completely different output than this:

int i;
List<Actionactions = new List<Action>();

for (i = 0; i < 5; i++)
{
int iT = i;

actions.Add(delegate { Console.WriteLine(iT); });
}

foreach (Action action in actions)
{
action();
}

The first outputs:

5
5
5
5
5

The second outputs:

0
1
2
3
4

This is because in the first case, each of the five anonymous methods
created are all sharing the same variable, "i". By the time the methods
get to execute, that variable has been set to the value "5". In the
second case, each of the five anonymous methods created get a different
variable, "iT", the value of which is set once to the value of "i" at the
time that the "iT" variable is created and never changed. So when the
anonymous methods get to execute, they each use the individual "iT"
variable created just for it.

This "capturing" behavior can be a bit confusing at first, but it turns
out to be very convenient in managing the data used by an anonymous
method. Of course, if you're not careful, it can wind up biting you; not
only do you have the issue demonstrated above in which the variable value
may change before the anonymous method gets to execute, if you're using
the anonymous method for implementing threading behavior, you could run
into thread synchronization problems.

Of course, by being careful to provide each anonymous method with its own
copy of the value, it's actually a nice way to _deal with_ thread
synchronization problems. So, it's a dual-edged sword, useful for good as
well as evil. :)

Pete
Sep 1 '08 #1
0 1393

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

Similar topics

4
by: No One | last post by:
Does anyone know if or when anonymous class support will be added to C#?
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: 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...
2
by: Gabe Moothart | last post by:
Hello, In one of my asp.net applications, I create a series of checkboxes, set their properties, and give them an "onChecked" event handler on the fly using an anonymous method. The code looks...
8
by: Red | last post by:
If auto-format is turned off in VS2008, there is apparently no way to indent a line. Under Tools->Options->Text Editor->C#->Formatting, there are three checkboxes. Unchecking those seems to cause...
2
by: Tony | last post by:
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...
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: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.