Sergejs
Sergejs

Reputation: 2580

How do I override virtual method with parameter that inherits base method parameter?

I have a set of objects inherited from ObjBase class. Processing logic is pretty same for all of these objects with a little differences. How do I keep all logic in public virtual void Work(ObjBase o) and process specific logic in overridden methods.

Example below is something I want to achieve, but it can't compile because of overriding parameters.

What be the better way to implement that ?

class Foo
{
    public void Do(ObjBase o)
    {
        switch (o.RequestType)
        { 
            case "A":
                new ProcA<ObjA>().Work(o);
                break;
            case "B":
                new ProcB<ObjB>().Work(o);
                break;
        }
    }
}

class ObjBase { }
class ObjA : ObjBase { }
class ObjB : ObjBase { }

class ProcBase
{
    public virtual void Work(ObjBase o)
    {
        //Common things to do...
    }
}

class ProcA<T> : ProcBase where T : ObjBase
{
    public override void Work(ObjA o)
    {
        base.Work(o);
        //DoSpecificWork
    }
}

class ProcB<T> : ProcBase where T : ObjBase
{
    public override void Work(ObjB o)
    {
        base.Work(o);
        //DoSpecificWork
    }
}

Thank you

Upvotes: 0

Views: 1154

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064324

Basically, you can't. I would advise that you put the custom code in the virtual method (i.e. also add an override), and cast - for example:

public override void Work(ObjBase o)
{
    base.Work(o);
    var a = o as ObjA;
    if (a != null)
    {
        // do a-specific things
    }
}

This ensures that your logic happens even if they call the base-type's method.

You could also provide a new overload, for example:

public void Work(ObjA o)
{
    Work((ObjBase)o);
}

But it is unclear that this adds much value.

Upvotes: 2

Related Questions