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)?
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With