3

I have several classes which inherit from a BaseClass which has an abstract method called GetData. In one of them I want to basically inherit from again and provide use a new method called GetArticles which I call from GetData. Here's the code.

public abstract class BaseClass
{
    internal abstract void GetData();
}

internal class FirstClass : BaseClass
{
    internal override void GetData()
    {
        // calls GetArticles
    }

    protected void GetArticles()
    {
    }
}

internal class SecondClass : FirstClass
{
    protected new void GetArticles()
    {
    }
}

GetArticles is never called in SecondClass. It calls the one in FirstClass, even though my object is of type SecondClass. I can't make GetArticles in FirstClass Abstract because I want to use FirstClass in its own right.

Any suggestions?

1
  • new does not override a method. Commented Feb 25, 2014 at 17:02

4 Answers 4

8

Your method has to marked as virtual in FirstClass and overriden using override keyword in SecondClass.

internal class FirstClass : BaseClass
{
    internal override void GetData()
    {
        // calls GetArticles
    }

    protected virtual void GetArticles()
    {
    }
}

internal class SecondClass : FirstClass
{
    protected override void GetArticles()
    {
    }
}

new modifier hides the underlying virtual method, which is not what you want. Check Knowing When to Use Override and New Keywords (C# Programming Guide) on MSDN.

7

Declare GetArticles in your FirstClass as virtual. In the second class remove new and add override

0
6

Make GetArticles virtual.

protected virtual void GetArticles()
{
}
-1

Normal Class can not contain abstract method.Whereas abstract class can contain normal method. If a normal class inherit abstract class and hold any abstract method than must be override due to inheritance in derived class.

2
  • An example would be really helpful. Commented May 21, 2020 at 14:19
  • I don't think this addresses his quesiton. Commented Dec 12, 2020 at 2:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.