0

I have a generic Command of type ICommand:

class SimpleCommand<T> : ICommand
{
    public SimpleCommand(Action<T> execute, Predicate<T> canExecute = null)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }
    /*
        All the other stuff...
    */
}

Used like this:

ICommand command = new SimpleCommand<string>(MyMethod);

private void MyMethod(string arg) { ... }

When using i would like the compiler to automaticly pick up the T from the Action passed, so i can just write like tihs:

ICommand command = new SimpleCommand(MyMethod);

However if i write like so, i get an compiler error. Is it possible to make the compiler pick up the T class from the Method parameter type ?

Anders
  • 1,590
  • 1
  • 20
  • 37

2 Answers2

2

You could implement static Create method.

public static class Command
{
    public static SimpleCommand<T> Create<T>(Action<T> execute, Predicate<T> canExecute = null)
    {
        return new SimpleCommand<T>(execute, canExecute);
    }
}

That should allow compiler to pick up the generic argument when called like:

ICommand command = Command.Create(MyMethod);
Euphoric
  • 12,645
  • 1
  • 30
  • 44
2

Not for a constructor, but you could implement the factory pattern which could instantiate the correct type based on the argument

Moho
  • 15,457
  • 1
  • 30
  • 31