-1

I want to pass a method from type (class) like a parameter to another method, I don't know how to do this.

    class Program
    {
        static void Main(string[] args)
        {
            MyMethod(Foo.MethodA);
            MyMethod(Foo.MethodB);
        }

        public void MyMethod(???)
        {
        }
    }

    public class Foo
    {
        public void MethodA()
        {
        }

        public int MethodB(int val)
        {
            return val;
        }
    }

I want to do just that

    MyMethod(Foo.MethodA);

I don't want to pass method from a object but just from type (class)

12
  • 2
    Use a Func type Commented May 12, 2021 at 20:44
  • Look up Delegate. The Func types (and the similar Action types) that @RufusL talks about are delegates. Commented May 12, 2021 at 20:47
  • stackoverflow.com/q/2082615/1070452 Commented May 12, 2021 at 20:51
  • 2
    Note that in your case, your Foo.MethodA() is a void function that has no parameters, while Foo.MethodB() takes an int as a parameter and returns an int. They are not the same type (well, other than they both can be represented as delegate). MethodA can be represented by an Action, while MethodB by a Func<int, int>. You'd need to work very hard to implement anything useful in MyMethod since the parameters passed in are so different Commented May 12, 2021 at 20:52
  • 2
    @JulioGold You really need to tell us what you want to do with the passed method, so we can figure out how to do what you want. Commented May 13, 2021 at 9:07

1 Answer 1

0

I'm not exactly sure what you are trying to do, but you can generalize methods as Delegate.

static void Main(string[] args)
{
    MyMethod(new Action(Foo.MethodA));
    MyMethod(new Func<int,int>(Foo.MethodB));
}

public static void MyMethod(Delegate del)
{
    // Example code
    var methodInfo = del.Method;
    var methodName = methodInfo.Name;
}

You will still need to wrap the method in some delegate like Action or Func<>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.