Different return types for the same base class method

Very simple base class:

class Figure { public virtual void Draw() { Console.WriteLine("Drawing Figure"); } } 

This inheriting class:

 class Rectangle : Figure { public int Draw() { Console.WriteLine("Drawing Rectangle"); return 42; } } 

The compiler will complain that the Rectangle "Draw" hides Draw Draw and asks to add either the new or override . Just adding new solves the following:

 class Rectangle : Figure { new public int Draw() //added new { Console.WriteLine("Drawing Rectangle"); return 42; } } 

However, Figure.Draw has a return type of void, Rectangle.Draw returns int. I am surprised that different types of returns are possible here ... Why is this?

+4
source share
4 answers

Have you really read the new modifier ?

Use the new modifier to explicitly hide an element inherited from the base class. To hide an inherited element, declare it in the derived class using the same name and change it with the new modifier.

So, you have hidden the version from the base class. The fact that these two methods have the same name does not mean anything - they are no more connected with each other than two methods whose names sound the same.


This situation should generally be avoided, but the compiler will always know which method should be called, and therefore whether it has a return value or not. If access to the "method" is as follows:

 Figure r = new Rectangle(); r.Draw(); 

Then the Figure Draw method will be called. The return value is not created and is not expected.

+6
source

What happens here is that you are hiding the base element method. Thus, the Draw method in Rectangle is a new method, as if this name was something else.

If you consume this element when the type is Rectangle , it will know the return type, but if you try to use this instance in the base type, the base method will be called with the return type.

+4
source

The new keyword simply tells the compiler that this method does not override the base, but has the same name. It will not be executed by a virtual call from the base class.

 class Base { public virtual void A() { Console.WriteLine("Base::A"); } public virtual void B() { Console.WriteLine("Base::B"); } } class Derived : Base { public override void A() { Console.WriteLine("Derived::A"); } public new int B() { Console.WriteLine("Derived::B"); } } 

So,

 Base obj = new Derived(); obj.A(); obj.B(); 

displays

 Derived::A Base::B 
+4
source

With the "new" keyword, you can only call int Draw from a Rectangle link. There is no runtime method permission.

 Rectangle r = new Rectangle(); Figure f = r; f.Draw(); // calls the void method Figure.Draw int x = r.Draw(); // calls the int method Rectangle.Draw 
+2
source

All Articles