Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my subclass required to override with default parameters?

I have a subclass which overrides a method in the base class. The base class's method has default parameters. My subclass is required to show those default parameters, although they need not be optionalized, in the 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 it is happy. I would expect it to accept a parameterless method signature, and then for it to be allowed to use the default parameter when base.MyMethod() is called.

Why does the subclass's method require a parameter?

like image 454
Evorlor Avatar asked Jan 04 '23 17:01

Evorlor


1 Answers

I would expect it to accept a parameterless method signature, and then for it to be allowed to use the default parameter when base.MyMethod() is called.

Your expectation is incorrect. Adding a default for a parameter does not mean that a method without the parameter exists. It just injects the default value into any calling code. So there is no method with no parameter to override.

You could explicitly create both overloads in the base class:

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

Then you could override either overload, but it's not clear from your question if that's appropriate.

like image 187
D Stanley Avatar answered Jan 14 '23 15:01

D Stanley