Func<>
is a generic delegate - it is just very convenient to use, because you don't have to create your own delegate for each argument/return type combination.
Earlier, you had to write something like:
public delegate long MyDelegate( int number );
public void Method( IEnumerable<int> list, MyDelegate myDelegate )
{
foreach( var number in list )
{
myDelegate( number );
}
}
You had to publish your delegate so that a user can call your method correctly. Especially when you need a bunch of different delegates you ended up publishing one for every argument list and return type.
With Func<>
you just write:
public void Method( IEnumerable<int> list, Func<int, long> myDelegate )
{
foreach( var number in list )
{
myDelegate( number );
}
}
It means the same as the first code example - Func<int, long>
defines a delegate that takes one integer argument and returns a long value.
Of course you can use longer parameter lists, too: Func<int, int, bool, long>
will still return a long value while it takes two ints and a bool value. If you wish a delegate without return value you will have to use Action<>
, which will have void as a return type.
EDIT (by request): How to call the method in my example:
For the caller, there is no difference between the solution with MyDelegate
or Func<>
. In both cases he has three options to call the method:
Using a lambda notation (C# 3.0 required, probably the best solution for short methods):
Method( myList, i => i * i );
By using an anonymous method (C# 2.0 required):
Method( myList, delegate( int i )
{
return i * i;
} );
Or by using a real method as an argument:
Method( myList, Square );
private static long Square( int number )
{
return number * number;
}