Explanation of Func

Are you familiar with delegates in general? I have a page about delegates and events which may help if not, although it’s more geared towards explaining the differences between the two. Func<T, TResult> is just a generic delegate – work out what it means in any particular situation by replacing the type parameters (T and … Read more

How can I pass in a func with a generic type parameter?

You cannot have instances of generic functions or actions – all type parameters are defined upfront and cannot be redefined by the caller. An easy way would be to avoid polymorphism altogether by relying on down-casting: public void SomeUtility(Func<Type, object, object> converter) { var myType = (MyType)converter(typeof(MyType), “foo”); } If you want type safety, you … Read more

Func delegate with ref variable

It cannot be done by Func but you can define a custom delegate for it: public delegate object MethodNameDelegate(ref float y); Usage example: public object MethodWithRefFloat(ref float y) { return null; } public void MethodCallThroughDelegate() { MethodNameDelegate myDelegate = MethodWithRefFloat; float y = 0; myDelegate(ref y); }

Does Ninject support Func (auto generated factory)?

NB Ninject 3.0 and later has this fully supported using the Ninject.Extensions.Factory package, see the wiki:- https://github.com/ninject/ninject.extensions.factory/wiki EDIT: NB there is a Bind<T>().ToFactory() implementation in Ninject 2.3 (which is not a fully tests supported release but is available from the CodeBetter server) Ninject does not support this natively at the moment. We planned to add … Read more

Why Func instead of Predicate?

While Predicate has been introduced at the same time that List<T> and Array<T>, in .net 2.0, the different Func and Action variants come from .net 3.5. So those Func predicates are used mainly for consistency in the LINQ operators. As of .net 3.5, about using Func<T> and Action<T> the guideline states: Do use the new … Read more

Delegates: Predicate vs. Action vs. Func

Predicate: essentially Func<T, bool>; asks the question “does the specified argument satisfy the condition represented by the delegate?” Used in things like List.FindAll. Action: Perform an action given the arguments. Very general purpose. Not used much in LINQ as it implies side-effects, basically. Func: Used extensively in LINQ, usually to transform the argument, e.g. by … Read more

Func vs. Action vs. Predicate [duplicate]

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action). Func is probably most commonly used in LINQ – for example in projections: list.Select(x => x.SomeProperty) or filtering: list.Where(x => x.SomeValue == someOtherValue) or key selection: list.Join(otherList, x => x.FirstKey, y => … Read more