Wednesday, June 25, 2008

IEnumerable Extention Methods and Action

This may be slightly off, but I've pretty much figured them out and how they work with lambda expressions. First off, Lambda expressions. These are the odd looking currentItem => expressions you might see in my examples. They are a little misleading, at least to me they were. When I saw:

 ilist.SomeExtension(currentItem => SomeMethod(currentItem));
I thought that meant: Loop through the list of currentItems and use that method. Well that's sort of it, but really misleading. In order to fully understand some of the more fun extension methods and lamba fun, a clearer explanation is needed. (I say fun instead of more complicated since I think the word "complicated" is exaggerating .) What

 ilist.SomeExtension(currentItem => SomeMethod(currentItem));
really means is that I am going to call this method SomeExtension, give it a method to use, and that's it. What it does with that method is the heart of what SomeExtension is. Small note: currentItem => helps to infer the type of whatever it is that you're going to pass into SomeMethod. Say SomeExtension looks like this:

public static void SomeExtension(this IList<I> items, <I>, Action<I> action)
{
   SomeExtension(I item in items)
  {
    action(item);
  }
}
Now what is action? It's basically a place holder for a method that returns nothing. Only thing it cares about is what it has to send in, and that is Type I. From there, it will call the method it points to and magic happens. Small note: What the hell is items? Well that is the list that you called this method from. This is an example of an extension method. Extension methods, in short, allow a person to "tack" a method onto a class without changing the class itself. this IList<I> items tells me that the extension method SomeExtension will be "tacked" onto ANY IList. In this instance, what action really looks like is this:

public void action
(
  delegate (I Item)
  {
    SomeMethod(item);
  }
)
As you can see, the SomeMethod from the original SomeExtension call comes into play now. The above examples really could be the List<> extention method of ForEach most likely looks like. Now what might not look familiar there is the delegate key word. This is what's called an anonymous method. Basically, this allows you to create delegates on the fly. An example of this would be List<>.Contains. A normal call to this might be:

someList.Contains(delegate(String currentItem){ return currentItem == someVariable); });
What this says is that contains will do whatever it does, but it will use the method you have provided to do that. Most likely the method itself looks like (And this is pseudo code for sure):

Boolean contains;

contains = false;

foreach(String currentItem in theList)
{
  contains = delegate(currentItem);

  if(contains)
  {
     exit;
  }
}

return contains;
Although, this is misleading in this post since this would deal with Func not Action.

No comments: