Consider the code
public class Base
{
public virtual int Add(int a,int b)
{
return a+b;
}
}
public class Derived:Base
{
public override int Add(int a,int b)
{
return a+b;
}
public int Add(float a,float b)
{
return (Int32)(a + b);
}
}
If I create an instance of Derived class and call Add with parameters of type int why it is calling the Add method with float parameters
Derived obj =new Derived()
obj.Add(3,5)
// why this is calling
Add(float a,float b)
Why it is not calling the more specific method?
This is by design. Section 7.5.3 of the C# language specification states:
In other words, because your
Derivedclass has a non-overriddenAddmethod, theAddmethod in theBaseclass (and its overridden version inDerived) are no longer candidates for overload resolution.Even though
Base.Add(int,int)would be a better match, the existance ofDerived.Add(float,float)means that the base class method is never even considered by the compiler.Eric Lippert discusses some of the reasons for this design in this blog post.