I'm trying to understand the differences between the Action<T>, Func<T> and Predicate<T>
delegates as part of my WPF/MVVM learning.
I know Action<T> and Func<T>
both take zero to one+ parameters, only Func<T>
returns a value while Action<T>
don't.
As for Predicate<T>
- I have no idea.
Therefore, I came up with this following questions:
- What does
Predicate<T>
do? (Examples welcomed!) - If
Action<T>
returns nothing, wouldn't it be simpler to just usevoid
instead? (Or any other type if it'sFunc<T>
we're talking about.)
I'd like you to avoid LINQ/List examples in your questions.
I've seen those already but they just make it more confusing as the code that got me 'interested' in these delegates have nothing to do with it (I think!).
Therefore, I'd like to use a code I'm familiar with to get my answer.
Here it is:
public class RelayCommand : ICommand
{
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
[DebuggerStepThrough]
public bool CanExecute(object parameters)
{
return _canExecute == null ? true : _canExecute(parameters);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameters)
{
_execute(parameters);
}
}
Note:
I took out the comments to avoid super-long block of code.
The full code can be found HERE.
Any help is appreciated! Thanks! :)
P.S: Please don't point me to other questions. I did try to search but I couldn't find anything simple enough for me to understand.