C# design: Why is new/override required on abstract methods but not on virtual methods?

Why is new/override required on abstract methods but not on virtual methods?

Sample 1:

abstract class ShapesClass
{
    abstract public int Area(); // abstract!
}

class Square : ShapesClass
{
    int x, y;

    public int Area() // Error: missing 'override' or 'new'
    {
        return x * y;
    }
}

The compiler will show this error: To make the current member override that implementation, add the override keyword. Otherwise add the new keyword

Sample 2:

class ShapesClass
{
    virtual public int Area() { return 0; } // it is virtual now!
}

class Square : ShapesClass
{
    int x, y;

    public int Area() // no explicit 'override' or 'new' required
    {
        return x * y;
    }
}

This will compile fine, by hiding the method by default.

I fully understand the technical differences. However I wonder why the language was designed that way. Wouldn't it be better to have the same restriction in "Sample 2" as well? I mean in most cases if you create a method with the same name as in the parent class, you usually intent to override it. So I think explicitly stating Override/New would make sense on virtual methods as well.

Is there a design-wise reason for this behavior?

Update: The 2nd sample actually causes a warning. The first sample shows an error because the subclass is required to implement the abstract method. I didn't see the warning in VS.. makes perfectly sense to me now. Thanks.

13
задан driAn 3 September 2010 в 10:45
поделиться