Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload resolution of virtual methods

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?

like image 224
Ashley John Avatar asked Jul 22 '11 12:07

Ashley John


People also ask

Can virtual method be overloaded?

Virtual methods can be overloaded in C#. Virtual methods can have both out and ref type parameters. If the derived class also has a method with the same name and signature as the base class virtual method, then the base class method will be hidden in the derived class.

What is overload resolution?

The process of selecting the most appropriate overloaded function or operator is called overload resolution. Suppose that f is an overloaded function name. When you call the overloaded function f() , the compiler creates a set of candidate functions.

What could be the advantages to use a virtual method?

The main advantage of virtual functions are that they directly support object oriented programming. When you declare a function as virtual you're saying that exactly what code is executed depends on the type of the object you call it against. you can't tell exactly what code path it's going to follow.

What are virtual methods?

What Does Virtual Method Mean? A virtual method is a declared class method that allows overriding by a method with the same derived class signature. Virtual methods are tools used to implement the polymorphism feature of an object-oriented language, such as C#.


1 Answers

This is by design. Section 7.5.3 of the C# language specification states:

For example, the set of candidates for a method invocation does not include methods marked override (§7.4), and methods in a base class are not candidates if any method in a derived class is applicable (§7.6.5.1).

In other words, because your Derived class has a non-overridden Add method, the Add method in the Base class (and its overridden version in Derived) are no longer candidates for overload resolution.

Even though Base.Add(int,int) would be a better match, the existance of Derived.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.

like image 188
Sven Avatar answered Sep 26 '22 23:09

Sven