Search code examples
c#lambdaaction

Delegate System.Action does not take 1 arguments


The action :

readonly Action _execute;

public RelayCommand(Action execute)
             : this(execute, null)
{
}

public RelayCommand(Action execute, Func<Boolean> canExecute)
{
    if (execute == null)
        throw new ArgumentNullException("execute");
    _execute = execute;
    _canExecute = canExecute;
}

Other class's code:

public void CreateCommand()
{
    RelayCommand command = new RelayCommand((param)=> RemoveReferenceExcecute(param));}
}

private void RemoveReferenceExcecute(object param)
{
    ReferenceViewModel referenceViewModel = (ReferenceViewModel) param;
    ReferenceCollection.Remove(referenceViewModel);
}

Why do I get the following exception, how can I fix it?

Delegate 'System.Action' does not take 1 arguments


Solution

  • System.Action is a delegate for parameterless function. Use System.Action<T>.

    To fix this, replace your RelayAction class with something like the following

    class RelayAction<T> {
        readonly Action<T> _execute;
        public RelayCommand(Action<T> execute, Func<Boolean> canExecute){
            //your code here
        }
        // the rest of the class definition
    }
    

    Note RelayAction class should become generic. Another way is to directly specify the type of parameter _execute will receive, but this way you'll be restricted in usage of your RelayAction class. So, there are some tradeoff between flexibility and robustness.

    Some MSDN links:

    1. System.Action
    2. System.Action<T>