Geeks With Blogs
Kyle Burns

In the last installment I discussed delegates, which have been in C# since version 1.  The problem with delegates in some cases is that having to create separate, named methods to describe the function to be performed can be a bit unwieldy in cases where the method being called is simple and will not be used other than by the delegate invocation.  This brings us to a feature added in C# 2.0 – anonymous methods.  Anonymous methods distilled down to their most simple explanation are methods that are defined inline in code and are not given a name (at least not by the developer).  An anonymous method is defined by using the delegate keyword and method parameters followed by the code block containing the method body.  If we go back to our first delegate example and use an anonymous method, it could be written as follows:

   1:  class Program
   2:  {
   3:      private delegate void PrintSomething(string message);
   5:      static void Main(string[] args)
   6:      {
   7:          PrintSomething func;
   8:          func = delegate(string message) { Console.WriteLine(message);};
   9:          func("My Message");
  10:          Console.ReadKey();
  11:      }
  12:  }

The fact the you get the convenience of not being required to define a separate method is nice, but there’s more than that to anonymous methods.  Anonymous methods also provide language support for closures in C#.  A closure is a programming construct that allows for a function to access variables that are outside of its typical scope.  Basically, the local variables of the method containing the closure remain in scope for the executing delegate.  This allows for anonymous methods to hit what I consider to be one of the real sweet spots for them in C# 2.0 – filtering and sorting generic lists.  The List<T> class contains several methods that have names starting with “Find” and include on their argument list an argument of type Predicate<T>, which is a delegate type defined in the Framework libraries.  Predicate<T> accepts a single argument of type T and returns a boolean.  When the Find method of a List<T> object is called, the predicate is called for each element in the list until one returns true.  If none of the predicate invocations return true, the Find method returns null.  Here’s an example of how Find and the closure functionality can be used together to search a list of strings:

   1:  List<string> names = new List<string>(new[]{ "Sam", "Fred", "Bill" });
   2:  string searchTerm = "Fred";
   3:  string result = names.Find(
   4:                             delegate(string expression) 
   5:                             { 
   6:                                 return expression.Equals(searchTerm, StringComparison.InvariantCultureIgnoreCase); 
   7:                             });

In this post, we briefly touched on the Predicate<T> delegate defined in the System namespace of the Framework libraries.  For those who feel like digging deeper, take a look as well at Action, Func, and other delegate types in the System namespace.

Posted on Monday, December 19, 2011 8:45 AM | Back to top

Comments on this post: The Road To LINQ-dom Part 3–Anonymous methods

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Kyle Burns | Powered by: