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 new
modifier?
Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
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:
Figure r = new Rectangle();
r.Draw();
Then Figure
s Draw
method will be invoked. No return value is produced, nor expected.
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