0

I am a beginner in C# and trying my hands on inheritance. ClassA is base class and classB and classC are derived from classA. My Program class has static method Show(). At first I was not sure whether I will be returning an objectB or objectC. So I did not know what should be return type of method Show(). Setting return type to base class i.e classA solved my problem at first, but when i tried to access MyMethod in Main it throws error because MyMethod is declared abstract in classA. How can I call MyMethod on my returned object?

abstract class classA
{
    protected abstract void MyMethod();
    // other fields and methods
}

class classB: classA
{
    protected override MyMethod()
    {
        //logic
    }
}

class classC: classA
{
protected override MyMethod()
    {
    //logic
    }
 }


class Program
{
    public static classA Show()
        {
            if(condition)
                { //logic
                return objectB;  //objectB is instantiated from classB
                }
            else
                {//logic
                return objectC;  //objectC is instantiated from classC
                }
        }

    static void Main(string[] args)
        {
         ClassA myObject = Show();
         myObject.MyMethod();
        }
}
1
  • Change MyMethod to public.
    – Aron
    Oct 31, 2013 at 1:04

1 Answer 1

1

You should make the MyMethod public.

abstract class classA
{
    public abstract void MyMethod();
    // other fields and methods
}

internal class classB : classA
{
    public override void MyMethod()
    {
        //logic
    }
}

internal class classC : classA
{
    public override void MyMethod()
    {
        //logic
    }
}

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.