Why should my subclass override the default options?

I have a subclass that overrides the method in the base class. The base class method has default parameters. My subclass should show these options by default, although they should not be optional, in an overridden method.

public class BaseClass
{
    protected virtual void MyMethod(int parameter = 1)
    {
        Console.WriteLine(parameter);
    }
}

public class SubClass : BaseClass
{
    //Compiler error on MyMethod, saying that no suitable method is found to override
    protected override void MyMethod()
    {
        base.MyMethod();
    }
}

However, if I change my method signature to

protected override void MyMethod(int parameter = 1)

or even

protected override void MyMethod(int parameter)

then he is happy. I would expect him to accept the signature without parameters, and then he would be allowed to use the default parameter when called base.MyMethod().

Why is a parameter required for a subclass method?

+4
source share
1 answer

, , base.MyMethod().

. , . . , .

:

protected virtual void MyMethod()
{
    MyMethod(1);
}
protected virtual void MyMethod(int parameter)
{
    Console.WriteLine(parameter);
}

, , .

+8

Source: https://habr.com/ru/post/1681809/


All Articles