I’d like write a function like the following
// The type 'MethodGroup' below doesn't exist. This is fantasy-code.
public void MyFunction(MethodGroup g)
{
// do something with the method group
}
The later, I could call MyFunction with any method group. Something like this.
MyFunction(Object.Equals)
If I commit to a signature, then things work fine.
public void MyFunction(Func<object, object, bool> f)
{
// do something with known delegate
}
...
MyFunction(Object.Equals)
The method group Object.Equals is happily coerced into the known delegate type Func<object, object, bool>, but I don’t want to commit to a particular signature. I’d like to pass any method group to MyFunction.
Method groups cannot be converted to System.Object
public void MyFunction(object o)
{
// do something with o
}
...
MyFunction(Object.Equals) // doesn't work
I think that everyone’s forgotten braces on a method call and discovered this at some point. I’m hoping that this doesn’t mean that method groups aren’t (or can’t be converted) to first class objects.
I don’t think that Linq expressions will give the kind of generality I’m looking for, but I could certainly be missing something.
I should also mention that it would be fine if the method group contained overloads, provided I have a way of inspecting the method group.
What would I do with a method group? I could print all the signatures of all the the methods in the group (overloads, extension methods etc), or I could ‘invoke’ the group with some arguments (have it resolve to the correct overload in the group if possible). There are other ways to do these things but they are some things you might want to do with a method group.
As several people have mentioned, I can accept a Delegate, and cast to a particular known delegate type when I call MyFunction.
public void MyFunction(Delegate d)
{
// do something with d
}
...
MyFunction((Func<object, object, bool>)Object.Equals)
But this isn’t quite the same as passing the entire method group. This selects one method from the group and converts it to a particular delegate. I would really like to pass the whole group in one shot.
You can pass a delegate :
However you will have to specify the delegate type when calling the method :
Note : the code above is not passing a method group but a single method… I don’t think it is possible to pass a method group. Why would you want to do that ?