A 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 Rectangle’s “Draw” hides the Figure’s Draw, and asks me to add either a new or override keyword. Just adding new solves this:
class Rectangle : Figure
{
new public int Draw() //added new
{
Console.WriteLine("Drawing Rectangle");
return 42;
}
}
However, Figure.Draw has a void return type, Rectangle.Draw returns an int. I am surprised different return types are allowed here… Why is that?
Did you actually read up on the
newmodifier?So, you’ve hidden the version from the base class. The fact that these two methods have the same name doesn’t mean anything – they’re no more related than two methods whose names sound the same.
Such a situation should generally be avoided, but the compiler will always know which method is to be called, and thus whether it has a return value or not. If “the” method is accessed as follows:
Then
FiguresDrawmethod will be invoked. No return value is produced, nor expected.