I’ve been seing Func<> for sometime now, and I’ve manage to avoid it (for now). But, now it looks like I can’t dodge it forever. For instance, I tried Dynamic Linq, but almost everything was in terms of Func<>. I’ve tried one of my book (C# 2008/Deitel&Deitel) and also MSDN but I’m not getting it yet. They all jump straight in the subject.
- What can be said (in few words) about Func<>
- Can I get some links on the web that can get me started on that matter?
Thanks for helping
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:
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: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 useAction<>, 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
MyDelegateorFunc<>. 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):
By using an anonymous method (C# 2.0 required):
Or by using a real method as an argument: