Search code examples
c#polymorphismvirtualoverriding

C# virtual methods override the return type & method arguments


I want to init virtual method with exact name in abstract class.

And in class, which is the inheritor override method such, that I can override:

  • the return type of the base method
  • arguments of the method

To show you, what I'm really want to do is smth like this:

abstract class A
{
    public virtual void Func1() { }
}

class B : A
{
    override string Func1(int a, int b)
    {
         return (a + b).ToString();
    }
}

I know, that C# requires to use the return type/args as in base class, but maybe there are some hints with keyword new in this situation?


Solution

  • You can only override the exact name and arguments. You can new whatever you want, but that's not overriding--just hiding in the case of an exact match.

    I think in your situation you will either want to create overloads for all possible combinations, or create a single base, abstract method which takes a single type that can contain the arguments you want.

    Example:

    public abstract void Func1( MyArgumentsType input );
    

    Now derived classes are compelled to override a method but you can pass a robust set of arguments to the method that can handle more scenarios.

    Polymorphism works to your advantage here, as you can then pass derived argument types to the method with situation-specific properties. Of course, this requires the implementing method to understand the more derived argument type.