473,396 Members | 1,996 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.

Importance of Anonymous Methods/Delegates

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 syntactic sugar (important as that can be)?

2. Are anonymous methods *required* anywhere? That is, are anonymous methods
the only way [or "by far" the easiest way] to accomplish certain tasks in
..NET programming?

Just trying to get a grip on where I might benefit from using anonymous
methods/delegates.

Thanks.
Sep 9 '07 #1
4 2359
Frankie,

1. Yes.

2. No. Wherever anonymous delegates are used, you could certainly create a
method/class which will do the same thing that the anonymous delegate does.
Granted, the fact that anonymous delegates are closures and encapsulate
local variables is not always easily duplicated is difficult to get around
at times, but not impossible.

Generally though, anonymous delegates are an improvement over having to
write full blown methods for simple actions that you need to have performed
in callbacks and events.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Frankie" <A@B.COMwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
>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 syntactic sugar (important as that can be)?

2. Are anonymous methods *required* anywhere? That is, are anonymous
methods the only way [or "by far" the easiest way] to accomplish certain
tasks in .NET programming?

Just trying to get a grip on where I might benefit from using anonymous
methods/delegates.

Thanks.
Sep 9 '07 #2
Frankie wrote:
Thank you Peter... RE:

<<they do really make it a LOT easier to deal with situations where you want
to use local variables (including method parameters) in the code. >>

Would an example of this [what you are talking about] be a situation where
an anonymous method is used in conjunction with the returning of a delegate
that makes use of an anonymous method, like this?:
...
return delegate() {... anonymous method here...}

or this?
....
someDelegateInstance += delegate {... anonymous method here...}
Since you didn't post any of the code inside the anonymous method, I
can't say whether those are an example of what I mean or not. In
particular, if the anonymous method doesn't reference any local
variables, then no...those aren't really examples of what I'm talking about.

If, on the other hand, they do reference local variables then
sure...those could be examples of what I'm talking about, even though
they aren't specifically what I had in mind.
If those do not qualify as examples of what you are talking about, can you
provide a brief example? Thanks!
Maybe Brian's reply has already elaborated this for you. But his
List.Find() example is exactly the sort of situation I had in mind. In
particular, .NET includes a lot of methods that take a predicate
delegate, used as a filter for some iterative process.

Often, you want the method implementing that predicate to be able to
make variable comparisons. That is, in some cases you can hard-code a
constant, but many situations call for passing in a value to use for a
comparison. In those cases, you need a place to put the value where the
method used for the predicate can get at it.

Without anonymous methods, the usual solution is to create a simple
class containing that value and the method. Then you instantiate the
class, initializing the value to the value you want, and creating the
predicate delegate using the method from the class:

class MyPredicateClass
{
int _i;

public MyPredicateClass(int i)
{
_i = i;
}

public bool MyPredicateMethod(int i)
{
return _i == i;
}
}

Then you use it in some method like this:

int MyIndexOf(List<intlist, int i)
{
MyPredicateClass mpc = new MyPredicateClass(i);

return list.FindIndex(mpc.MyPredicateMethod);
}

(Of course, the above is extremely simplistic, and already fully
supported by List<without using predicates...in a real situation, the
predicate method would usually be doing a more complex evaluation. But
for the purposes of illustration, I think the simpler code is better).

Note the simple MyPredicateClass, the only purpose for which is to store
some data used by the predicate method. Using an anonymous method you
could do this much more simply as follows:

int MyIndexOf(List<intlist, int iFind)
{
return list.FindIndex(
delegate(int iObj) { return iObj == iFind; } );
}

The magic here is that the "iFind" local variable is "captured" by the
anonymous method, allowing it to be used by that method when it's used
as a predicate, without having to explicitly store it somewhere.

This sort of advantage is not by any means limited to anonymous methods
used as predicates. It just happens that the predicate scenario is a
fairly common and easily-explain example.

In the simplest cases, this is all you really need to know. You can
start using anonymous methods, making lots of good use of them, with
just the above information. Watch out though...anonymous methods do
carry the potential for some strange complications. :) Read on...

Even if the anonymous method is used asynchronously, variables are still
captured and can live on past the lifetime of the scope where the
anonymous method was declared. For many situations this isn't an issue;
even if the anonymous method is used asynchronously (for example, as the
argument for a call to Control.BeginInvoke(), a reasonably common
asynchronous technique), often the variable being passed is a just a value.

But if it's a reference type, and the object is mutable, then some other
code could change the object after the asynchronous call was made, but
before the anonymous method is actually executed, or the anonymous
method could asynchronously affect other code using the same object (if
it modifies the object). Similarly, local variables that are arguments
passed by reference ("out" or "ref") still act in the same way that they
would in the method to which they were passed, introducing some
potentially difficult synchronization issues.

So, with the added power of anonymous methods comes great responsibility
to use them wisely. But isn't that always the case? :)

Pete
Sep 9 '07 #3
Thank you Peter so much! Your example with a predicate delegate not only
illustrates the point very well, but provides a more elegant solution to a
hack I threw together about a year ago with predicate delegates... time to
refactor now that I have a better understanding of anonymous methods.

-F
"Peter Duniho" <Np*********@NnOwSlPiAnMk.comwrote in message
news:13*************@corp.supernews.com...
Frankie wrote:
>Thank you Peter... RE:

<<they do really make it a LOT easier to deal with situations where you
want to use local variables (including method parameters) in the code. >>

Would an example of this [what you are talking about] be a situation
where an anonymous method is used in conjunction with the returning of a
delegate that makes use of an anonymous method, like this?:
...
return delegate() {... anonymous method here...}

or this?
....
someDelegateInstance += delegate {... anonymous method here...}

Since you didn't post any of the code inside the anonymous method, I can't
say whether those are an example of what I mean or not. In particular, if
the anonymous method doesn't reference any local variables, then
no...those aren't really examples of what I'm talking about.

If, on the other hand, they do reference local variables then sure...those
could be examples of what I'm talking about, even though they aren't
specifically what I had in mind.
>If those do not qualify as examples of what you are talking about, can
you provide a brief example? Thanks!

Maybe Brian's reply has already elaborated this for you. But his
List.Find() example is exactly the sort of situation I had in mind. In
particular, .NET includes a lot of methods that take a predicate delegate,
used as a filter for some iterative process.

Often, you want the method implementing that predicate to be able to make
variable comparisons. That is, in some cases you can hard-code a
constant, but many situations call for passing in a value to use for a
comparison. In those cases, you need a place to put the value where the
method used for the predicate can get at it.

Without anonymous methods, the usual solution is to create a simple class
containing that value and the method. Then you instantiate the class,
initializing the value to the value you want, and creating the predicate
delegate using the method from the class:

class MyPredicateClass
{
int _i;

public MyPredicateClass(int i)
{
_i = i;
}

public bool MyPredicateMethod(int i)
{
return _i == i;
}
}

Then you use it in some method like this:

int MyIndexOf(List<intlist, int i)
{
MyPredicateClass mpc = new MyPredicateClass(i);

return list.FindIndex(mpc.MyPredicateMethod);
}

(Of course, the above is extremely simplistic, and already fully supported
by List<without using predicates...in a real situation, the predicate
method would usually be doing a more complex evaluation. But for the
purposes of illustration, I think the simpler code is better).

Note the simple MyPredicateClass, the only purpose for which is to store
some data used by the predicate method. Using an anonymous method you
could do this much more simply as follows:

int MyIndexOf(List<intlist, int iFind)
{
return list.FindIndex(
delegate(int iObj) { return iObj == iFind; } );
}

The magic here is that the "iFind" local variable is "captured" by the
anonymous method, allowing it to be used by that method when it's used as
a predicate, without having to explicitly store it somewhere.

This sort of advantage is not by any means limited to anonymous methods
used as predicates. It just happens that the predicate scenario is a
fairly common and easily-explain example.

In the simplest cases, this is all you really need to know. You can start
using anonymous methods, making lots of good use of them, with just the
above information. Watch out though...anonymous methods do carry the
potential for some strange complications. :) Read on...

Even if the anonymous method is used asynchronously, variables are still
captured and can live on past the lifetime of the scope where the
anonymous method was declared. For many situations this isn't an issue;
even if the anonymous method is used asynchronously (for example, as the
argument for a call to Control.BeginInvoke(), a reasonably common
asynchronous technique), often the variable being passed is a just a
value.

But if it's a reference type, and the object is mutable, then some other
code could change the object after the asynchronous call was made, but
before the anonymous method is actually executed, or the anonymous method
could asynchronously affect other code using the same object (if it
modifies the object). Similarly, local variables that are arguments
passed by reference ("out" or "ref") still act in the same way that they
would in the method to which they were passed, introducing some
potentially difficult synchronization issues.

So, with the added power of anonymous methods comes great responsibility
to use them wisely. But isn't that always the case? :)

Pete

Sep 10 '07 #4
Frankie wrote:
Thank you Peter so much! Your example with a predicate delegate not only
illustrates the point very well, but provides a more elegant solution to a
hack I threw together about a year ago with predicate delegates... time to
refactor now that I have a better understanding of anonymous methods.
You're welcome...I'm glad you found the information helpful. :)
Sep 10 '07 #5

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#?
2
by: Marcos Stefanakopolus | last post by:
In C# is there any way to use the concept of delegates to have multiple implementations of a particular block of code, so that you can choose between them without the overhead of possibly expensive...
3
by: anonymous | last post by:
I believe I ran into an interesting way to create memory leaks in C# 2.0 using anymous delegates. Here is a sample of the code in question. private void Handle_Event(object sender, EventArgs e)...
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. ...
4
by: Harold Howe | last post by:
I am running into a situation where the compiler complains that it cannot infer the type parameters of a generic method when one of the function arguments is an anonymous method. Here is a...
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...
15
by: Matt | last post by:
Hi There, Can anyone explain me the real advantages of (other than syntax) lambda expressions over anonymous delegates? advantage for one over the other. delegate int F(int a); F fLambda = a...
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: 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
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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.