Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading with generics. Is it expected behaviour? [duplicate]

Tags:

c#

Possible Duplicate:
A problem with generic method overloading

Here is a simple code:

static class Example  
{  
    static int DoIt(object o) { return 0; }    
    class A { }
    static int DoIt(A a) { return 1; }
    static int CallDoIt<X>(X x) { return DoIt(x); }
    static void Main()
    {
        var a = new A();
        System.Console.WriteLine(DoIt(a));      // returns 1 (as desired)
        System.Console.WriteLine(CallDoIt(a));  // returns 0
    }
}

The result looks very strange: the function DoIt() called directly returns different value from the case when it is called from another function. Is it expected behaviour in C#? If yes, how to achieve the desired behaviour (preferably without reflection)?

like image 386
user2016189 Avatar asked Aug 14 '26 14:08

user2016189


1 Answers

This is the expected behaviour, the knowledge of what type X is does not extend into the CallDoIt function. The overload of DoIt called from CallDoIt is determined statically based on the type of the argument x. Since X can be anything, the best (and only) candidate is DoIt(object).

You can get around this behaviour by delaying the dispatch to DoIt until runtime using dynamic:

static int CallDoIt<X>(X x) { return DoIt((dynamic)x); }

The other alternative is to provide a more specific version of CallDoIt:

static int CallDoIt(A a) { return DoIt(a); }
like image 96
Lee Avatar answered Aug 17 '26 02:08

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!