0

Is there a way to pass a method as a parameter without knowing anything about the method in advance?

Can Func<input, return> be called without knowing the method's parameter/return type?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
sd_dracula
  • 3,796
  • 28
  • 87
  • 158

4 Answers4

6

The closest you can come is to use Delegate - the caller will need to pick the right delegate type. That's exactly why Control.Invoke uses Delegate instead of a specific delegate type.

Alternatively, there's MethodInfo as HackedByChinese suggests. Which one you should use depends on what you're trying to achieve - each is useful in different contexts. If you're trying to describe a method, then MethodInfo is probably the best approach. If you're trying to represent a callable action of some kind (which can take parameters and have a return value) then a delegate is probably more useful.

If you tell us more about what you're trying to achieve, we may be able to help you more.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

It sounds that invoking a method via reflection would be what you're interested in.

See MethodInfo.

moribvndvs
  • 42,191
  • 11
  • 135
  • 149
2

you need to use a delegate to do that. There are several posts on Stackoverflow that cover that.

I suggest this, specially Jon Skeet answer

Community
  • 1
  • 1
Diego
  • 34,802
  • 21
  • 91
  • 134
2

Seems that you could be overengineering here.. You should properly look at the surrounding infrastructur in you code, and try to refactor that instead.

But if you really need to, you can do it with generics. Now, I would not recommend this - but this function you could call with anything, you would have to define Y and T and call time.

    public virtual Y MyWrapperFunction<T,Y>(Func<T,Y> func, T param)
    {
        return func(param);
    }

But be warned - generics can give you all sorts of different problems ;)

Sandbeck
  • 366
  • 1
  • 3
  • Thanks for the replies.Basically I'm trying to pass a method into an Exception handler wrapper that uses enterprise library 5 exception handling. I'm trying to pass any method into it and now have to create as many methods as I already have, just use one. – sd_dracula May 15 '12 at 13:32