Pacha
Pacha

Reputation: 1526

calling parent methods from overriden class in C#

I have the following code:

class ClassA
{
    public virtual void DoSomething()
    {
        DoSomething(1); // when called from ClassB, it calls DoSomething from ClassA with an infinite recursion
    }

    public virtual void DoSomething(int someInt)
    {
        // do something
    }
}

class ClassB : ClassA
{
    public override void DoSomething()
    {
        DoSomething(1);
    }
    public override void DoSomething(int someInt)
    {
         base.DoSomething(someInt);

        // do something
    }
}

class Program
{
    void someMethod()
    {
        ClassB instance = new ClassB();
        instance.DoSomething(); // stack overflow caused by infinite recursion
    }
}

My problem is that when I call ClassB.DoSomething(); and it calls base.DoSomething(someInt); I want the parent class which ClassB is derived to call ClassA's method instead of the overriden one.

Is there a way to do this in a clean way without copying/pasting repeated code?

Upvotes: 0

Views: 121

Answers (2)

Servy
Servy

Reputation: 203802

You can modify the base class like so:

class ClassA
{
    public virtual void DoSomething()
    {
        DoSomethingHelper(1); // when called from ClassB, it calls DoSomething from ClassA with an infinite recursion
    }

    public virtual void DoSomething(int someInt)
    {
        DoSomethingHelper(someInt);
    }

    private void DoSomethingHelper(int someInt)
    {
        // do something
    }
}

By refactoring out the entire method into a private method you provide a means to call the current class' definition of the method while still providing a virtual method for the child class to access.

Upvotes: 2

Nick Bray
Nick Bray

Reputation: 1963

When you override the virtual method you can't call it without the base keyword, so you cannot cal if from that class. You can try using what Jon B said and use method shadowing instead of overriding.

class ClassA
{
    public void DoSomething()
    {
        DoSomething(1); 
    }

    public void DoSomething(int someInt)
    {
        Console.WriteLine("a");
    }
}

class ClassB : ClassA
{
    public new void DoSomething()
    {
        DoSomething(1);
    }

    public new void DoSomething(int someInt)
    {
        base.DoSomething();
    }
}

Upvotes: 0

Related Questions