SumGuy
SumGuy

Reputation: 622

Inject into inheritance

Is it possible to repurpose a call in an inherited class, I need to do some additional things to the context in TheFirstClass prior to and after having TheLastClass process the context. Ideally I want to not have to rename the process override in all instances of TheLastClass. I tried to just add another abstract class, but the inheritance prevents a second abstract class of the same name.

void Main()
{
    var context = new ContextClass();
    var LastClass = new TheLastClass();
    LastClass.CallTheProcess(context);
}

// Define other methods and classes here
abstract class TheBaseClass
{
    public abstract void Process(ContextClass context);

    public void CallTheProcess(ContextClass context)
    {
        // other necessary stuff
        context.test = "Base Class";
        Process(context);
    }
}

class TheFirstClass : TheBaseClass
{   
    //public abstract void Process(ContextClass context)
    public override void Process(ContextClass context)
    {
        context.test = "success";
        Process(context);//How can I call inherited overrides? and not infinite loop
    }
}

class TheLastClass : TheFirstClass
{
    public override void Process(ContextClass context)
    {
        //do stuff with the context
        if(context.test == "success")
        {
            "ThisWorked".Dump();
            //how do I get here?
        }
    }
}

class ContextClass
{
    public string test;
}

Upvotes: 1

Views: 78

Answers (1)

Pajdziu
Pajdziu

Reputation: 920

You can use the base keyword.

void Main()
{
    var context = new ContextClass();
    var LastClass = new TheLastClass();
    LastClass.CallTheProcess(context);
}


abstract class TheBaseClass
{
    public abstract void Process(ContextClass context);

    public void CallTheProcess(ContextClass context)
    {
        this.Process(context); 
        // other necessary stuff
        context.test = "Base Class";
    }
}

class TheFirstClass : TheBaseClass
{   
    public override void Process(ContextClass context)
    {
        context.test = "success";
        // some operations
    }
}

class TheLastClass : TheFirstClass
{
    public override void Process(ContextClass context)
    {
        base.Process(context); // from the TheFirstClass
        // other operations
    }
}

and then, if you call LastClass.CallTheProcess(context); you'll get this order:

  1. TheBaseClass.CallTheProcess
  2. TheFirstClass.Process
  3. TheLastClass.Process (//other operations part)

Upvotes: 4

Related Questions