A Func<int, string> eats ints and returns strings. So what eats ints and returns strings? How about this ...
public string IntAsString( int i ) { return i.ToString(); }
There I just created a function that eats ints and returns strings. How will I use it?
var lst = new List<int>() { 1, 2, 3, 4, 5 }; string str = String.Empty; foreach( int i in lst ) { str += IntAsString(i); }
Not very sexy, I know, but this is a simple idea on which many tricks are based. Now use Func instead.
Func<int, string> fnc = IntAsString; foreach (int i in lst) { str += fnc(i); }
Instead of calling IntAsString for each element, I created a link to it with the name fnc (these method links are called delegates ) and are used instead. (Remember that fnc eats ints and returns strings).
This example is not very sexy, but the ton of smart things you will see is based on the simple idea of ββfunctions, delegates, and extension methods .
One of the best primers on this material that I have seen is here . He got much more real examples. :)
JP Alioto May 18 '09 at 17:18 2009-05-18 17:18
source share