Mike Irish
Mike Irish

Reputation: 960

Is it possible to use if condition in base class to effect child class

I am trying to figure out if it is possible to use an if statment in a base class and depending on the value either continue execution of the parent class method or just return.

here is a small example I made.

main class to create two parent classes

public class Program
{
    public static void Main()
    {
        Class1 c1 = new Class1();

        Class2 c2 = new Class2();

        c1.test();

        c2.test();

    }
}

This is the base class that contains the method to be ovveridden

public class baseClass
{

    public bool b = true;

    public virtual void test()
    {
        if(!b)
        {
            Console.WriteLine("b is true returning");
            return;
        }
    }
}

Parent Class 1

public class Class1 : baseClass
{
    public override void test()
    {
        base.test();

        //the below line should only execute if b is true
        Console.WriteLine("Executing a method unique to Class1");
    }
}

Parent Class 2

public class Class2 : baseClass
{
    public override void test()
    {
        b = false;
        base.test();

        //the below line should only execute if b is true
        Console.WriteLine("Executing a method unique to Class2");
    }
}

I really simplified it there and it looks kind of pointless but I am trying to explain what I want to do with code.

Basically in my base class I will check if a list is empty and if it is I just want to return and not continue execution of the parent class method. However if it is not empty each parent class will do something different with the list.

EDIT Here is a fiddle, What I am trying to achieve is it should not print out the line from Class2.test()

https://dotnetfiddle.net/p67UgJ

Upvotes: 0

Views: 892

Answers (1)

Philip Smith
Philip Smith

Reputation: 2801

You need to separate the part of the method you want to override, rather than override the whole method.

public class baseClass
{
    public bool b = true;

    public void test()
    {
        if(!b)
        {
            BitThatNeedsToChange();
            return;
        }
    }

    protected virtual void BitThatNeedsToChange()
    {
        Console.WriteLine("b is true returning");
    }
}

In your derived classes you would override the protected virtual method:

public class Class1 : baseClass
{
    protected override void BitThatNeedsToChange()
    {
        //the below line should only execute if b is true
        Console.WriteLine("Executing a method unique to Class1");
    }
}

Upvotes: 3

Related Questions