Search code examples
c#delegatesicommand

RelayCommand and delegates, trying to understand delegates


I need some help to understand what delegates is, and if I have used it in my program. I'm using the RelayCommand class which I found in another stack post to implement my commands.

RelayCommand:

public class RelayCommand : ICommand
{
    readonly Action<object> _execute;
    readonly Func<bool> _canExecute;

    public RelayCommand(Action<object> execute, Func<bool> canExecute = null)
    {
        if (execute == null)
            throw new ArgumentNullException(nameof(execute));

        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute.Invoke();
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

In my ViewModel's constructor, I am doing this:

 public ICommand SearchCommand { get; set; }

 //Constructor
 public BookingViewModel()
 {
     SearchCommand = new RelayCommand(SearchCommand_DoWork, () => true);     
 }

 public async void SearchCommand_DoWork(object obj)
 {
  //Code inside this method not shown
 }

I know that a delegate is a type that encapsulate a method. You can write a delegate like this:

public delegate int MethodName(string name)

Where the delegate is encapsulating the method MethodName that has a return type of int and takes a parameter of a string.

Does this mean that there is a delegate created when using ICommand like i shown in the code? Where the encapsulating method is "SearchCommand_DoWork"

Hope some one can clear some things out for me.


Solution

  • Does this mean that there is a delegate created when using ICommand like i shown in the code? Where the encapsulating method is "SearchCommand_DoWork"

    You're creating a new object of type RelayCommand. As you can see in the class' constructor, you're passing in an Action object (delegate that returns no value) and a Func object (delegate that returns a value).

    For the Action delegate you're passing in an object that encapsulates the void function SearchCommandDoWork, for the Func object you're passing in an lambda function that takes no parameter and always returns true.

    The Action delegate encapsulates your SearchCommand_DoWork function (a delegate is basically a type safe function pointer).

    Both Action and Func are predefined delegates. You can also define your own delegates, which is what

    public delegate int MethodName(string name)
    

    does.