tags:

views:

342

answers:

2

I have a generic collection (Dictionary), which stores an enum and delegate. So if the user provides an enum value to a method as a parameter, the corresponding delegate in the collection will get executed.

This method, which the delegate points to, is overloaded. When invoking the method, how can I choose which version of the method to execute?

Thanks

A: 

A delegate as a specific signature. When you instance a delegate with a Method that has overloads it will use the overload whose signature best matches the delegates signature.

AnthonyWJones
This is the only way really. I could just wrap the delegates in a seperate class and perhaps invoke the desired delegate. A little bit of a hack, but I will try this.
dotnetdev
+3  A: 

The delegate only points to a single overload - not to the "method group". By the time you get a delegate to a method, you have already done overload resolution. Usually, you can do this just in the compiler:

using System;
class Foo {
    int Bar() { return 1; }
    void Bar(int a) { }
    static void Main() {
        Foo foo = new Foo();
        Func<int> myDelegate = foo.Bar; // points to "int Bar()" version
    }
}

If the question relates to getting the overloaded method via reflection - then you can specify the pattern in the arguments to Type.GetMethod() (as a Type[]). This should give you the method you want.

To get a delegate from a MethodInfo, use Delegate.CreateDelegate.

Marc Gravell
I guess I could just store different delegate types in the collection. As the delegate itself has certain enforced properties (return type/parameters), it's a little shortsighted of me to ask how to invoke other overloads.
dotnetdev
If you are storing different delegate types, are you using DynamicInvoke? That is very *slow* compared to storing a single type of delegate and using the typed Invoke.
Marc Gravell
I was using Invoke(). However, the code is a WIP. Thanks (I learn something new and realise a topic to look up in every one of your replies).
dotnetdev