Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different return type for same method of a base class

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?

like image 586
Konerak Avatar asked Dec 04 '22 15:12

Konerak


1 Answers

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 Figures Draw method will be invoked. No return value is produced, nor expected.

like image 145
Damien_The_Unbeliever Avatar answered Dec 10 '22 09:12

Damien_The_Unbeliever