Delegates => Lambdas, Pt. 2: Anonymous Methods == Inline Delegates

This is a series I created on my company's internal intranet for a few young developers.  However, I thought it might be useful to anyone, so I wanted to make it public.


In my last post, I introduced delegates and briefly showed you how to use them, along with explaining a few of the benefits.  At the same time, there were some drawbacks as well that I probably didn't mention, but may have hinted at.

I suggest you look at that post again to refresh your memory about how delegates are declared and used.  The first thing you might notice that is a little less than ideal about the last example is that you still need to declare a function for each of your filters - IsEasternConferenceTeam, TeamNameStartsWithB, etc.  At that point, why don't you just call them directly in your code instead of passing them into another function?

This is where anonymous methods come in.  Anonymous methods allow you to declare methods inline using the delegate keyword.  This cuts down on unnecessary private functions bulking up your code.

Let's take a look at an example.  As a quick refresher, in the last post, we had this for filtering:

   1:  private static bool IsEasternConferenceTeam(TeamDTO team)
   2:  {
   3:       return team.Conference == "East";
   4:  }
   5:   
   6:  private static bool TeamNameStartsWithB(TeamDTO team)
   7:  {
   8:       return team.TeamName.StartsWith("B");
   9:  }
  10:   
  11:  IList<TeamDTO> allTeams = new List<TeamDTO>
  12:                                            {
  13:                                                new TeamDTO("Flyers", "East"),
  14:                                                new TeamDTO("Blackhawks", "West"),
  15:                                                new TeamDTO("Blue Jackets", "West"),
  16:                                                new TeamDTO("Capitals", "East")
  17:                                            };
  18:   
  19:  IList<TeamDTO> easternTeams = SelectTeamsByFilter(allTeams, IsEasternConferenceTeam); // will return a list wtih Flyers and Capitals
  20:   
  21:  IList<TeamDTO> teamsThatStartWithLetterB = SelectTeamsByFilter(allTeams, TeamNameStartsWithB); // will return a list with Blackhawks and Blue Jackets

Those two functions at the top are really just different filters. Seems a little bulky. So with anonymous methods we can do this instead:

   1:  IList<TeamDTO> allTeams = new List<TeamDTO>
   2:                                            {
   3:                                                new TeamDTO("Flyers", "East"),
   4:                                                new TeamDTO("Blackhawks", "West"),
   5:                                                new TeamDTO("Blue Jackets", "West"),
   6:                                                new TeamDTO("Capitals", "East")
   7:                                            };
   8:   
   9:  IList<TeamDTO> easternTeams = SelectTeamsByFilter(allTeams, delegate(TeamDTO team) { return team.Conference == "East"; });
  10:   
  11:  IList<TeamDTO> teamsThatStartWithLetterB = SelectTeamsByFilter(allTeams, delegate(TeamDTO team) { return team.TeamName.StartsWith("B"); });

Now - we can get rid of those functions.  And we can write whatever types of filters we want inline in code wherever we need to filter things.

Again - notice that as long as long as the contract is fulfilled for this delegate (TeamDTO input, boolean output), there will be no complaints from the compiler.  And just like I mentioned before, these functions can actually do as much as work as you'd like them to - they don't need to be just one line.  Of course, when you get into writing them inline like this, big functions that do a lot of heavy lifting quickly become hard to format.  But for quick one-liners, I think this is awesome.  And imagine, like I mentioned in my last post, how easy it is now for consumers of this code to write new filters?

The next step is from anonymous methods to lambdas.

Print | posted @ Thursday, August 13, 2009 1:12 PM

Comments on this entry:

No comments posted yet.

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 6 and 4 and type the answer here: