Can someone provide a good explanation (hopefully with examples) of these 3 most important delegates:
- Predicate
- Action
- Func
What other delegates should a C# developer be aware of?
How often do you use them in production code?
Can someone provide a good explanation (hopefully with examples) of these 3 most important delegates:
What other delegates should a C# developer be aware of?
How often do you use them in production code?
Predicate, Func and Action are inbuilt delegate instances of .NET. Each of these delegate instances could refer or point to user methods with specific signature.
Action delegate - Action delegate instances could point to methods that take arguments and returns void.
Func delegate - Func delegate instance could point to method(s) that take variable number of arguments and return some type.
Predicate - Predicates are similar to func delegate instances and they could point to methods that take variable number of arguments and return a bool type.
Action
,Func
andPredicate
all belong to the delegate family.Action
: Action can take n input parameters but it returns void.Func
: Func can take n input parameters but it will always return the result of the provided type.Func<T1,T2,T3,TResult>
, here T1,T2,T3 are input parameters and TResult is the output of it.Predicate
: Predicate is also a form of Func but it will always return bool. In simple words it is wrapper ofFunc<T,bool>
.Func is more LINQ friendly, can be passed in as a parameter. (point-free)
Predicate cannot, has to be wrapped again.
Predicate
: essentiallyFunc<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 projecting a complex structure to one property.Other important delegates:
EventHandler
/EventHandler<T>
: Used all over WinFormsComparison<T>
: LikeIComparer<T>
but in delegate form.MethodInvoker is one which WinForms developers may use; it accepts no arguments and returns no results. It predates Action, and is still often used when invoking onto the UI thread since BeginInvoke() et al accept an untyped Delegate; although Action will do just as well.
I'd also be aware of ThreadStart and ParameterizedThreadStart; again most people will substitute an Action these days.
Action and Func with lambda: