Jano's Software Ramblings
Code & Pray from Monterrey

C# Tip #5: Anonymous delegates

September 6, 2007 02:04 by Jano

The first idea of anonymous delegates is to do your code a little cleaner specially for one-time functions. But there are two things for which I actually like them better.  First, it comes to style, it is part of C# constant move to a dynamic language. Even in version 1.0 C# included autoboxing (inferring how you wanted to use primitives), but in C# 2.0 it began creating delegates for you and in Asp.net, for example, turned DataBinder.Eval(Container.DataItem, "MyProperty") into Eval("MyProperty"), which I thought was a huge step foward. In C# 2.0 the compiler infer part of the signature of your method by looking in the return value. So in:

delegate(string s)

{

    return s.Length;  

The compiler automatically knows you are returning an integer. The future looks bright for us who love dynamic programming, since C# 3.0 includes var variables (which aren't variants just inferred) and anonymous classes (Tuple ugly cousin).  The second reason I love delegates is that you can use local variables, so it makes posible code that would be otherwise difficult or imposible. 

 private List<string> myList = new List<string>(new string[]{"Alex", "Jerry", "Joe", "Jimmy", "Dean"});

So you can  easily built a method that searches for all names that starts  with a certain letter.

public string[] FindAllStartsWitch(char c)

{

    return myList.FindAll(delegate(string s){return s[0]==c}).ToArray();  

C# 3.0 even includes lamda functions which will make the code even cleaner.  


Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments are closed