|Anonymous Methods In C#|
|Written by Mike James|
|Tuesday, 01 April 2014|
Page 2 of 2
Using anonymous methods
So what are anonymous methods good for?
They certainly save one level of naming confusion but in some cases they can remove the need for any new names at all.
For example, consider the Find method of the Array object defined as:
The Predicate delegate is defined as:
Without anonymous methods you would have to define a Predicate method, wrap in a delegate and pass it to the Find method.
With anonymous method it can be as simple as:
In short, anonymous methods are good for short functions that you want to use “at once”, often as a parameter within a method call.
In version 3.0 of .NET anonymous methods were augmented by lambda expressions - and this often causes confusion about which facility does what.
A lambda expression can be considered an even lighter weight anonymous method.
You still need to define a delegate type and this determines the number and type of the parameters used in the lambda expression. The basic idea is that the method is simply assigned to the delegate instance using a special notation:
Apart from this change a lambda expression can be treated exactly like an anonymous method.
For example, our previous "Hello" example can be written:
In the same way the Array.Find example can be written:
Notice that in this case, as there is only a single parameter, x, we can also follow the convention of dropping the brackets making it look even simpler.
The bottom line is that lambda expressions are just a shorthand way of creating anonymous methods.
However this doesn't mean that they aren't worth using or that they don't have any interesting subtleties that deserve further exploration.
Both anonymous methods and lambda expressions bring with them an interesting additional facility.
As both are declared within the context and scope of an enclosing method there is the possibility of defining how the enclosing and enclosed method can interact - and this brings us to the fascinating and useful topic of closure, the topic of another article.
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
or email your comment to: firstname.lastname@example.org
|Last Updated ( Tuesday, 20 September 2016 )|