Method overriding in C# – part 3

Let’s analyze just one more example of method overriding. In this case we have got three classes. TopClass is derived from IntermediateClass. IntermediateClass is derived from BaseClass. What if we are in the TopClass level and we want to perform some operations at the lower level and then go back, to the top level?

Well, look at the SomeJob method:

C# code

 class Program
    {
        static void Main(string[] args)
        {
            BaseClass bc = new BaseClass();
            bc.InvokeMethod();

            IntermediateClass ic = new IntermediateClass();
            ic.InvokeMethod();

            TopClass tc = new TopClass();
            tc.SomeJob();

            Console.ReadLine();
        }
    }

    public class BaseClass
    {
        public virtual void InvokeMethod()
        {
            Console.WriteLine("This is the base method");
        }
    }

    public class IntermediateClass : BaseClass
    {
        public override void InvokeMethod()
        {
            Console.WriteLine("This is the intermediate method");
        }

        public void IntermediateMethod()
        {
            // let's do another job here
            Console.WriteLine("Some job from Intermediate class level");
            InvokeMethod();
        }
    }

    public class TopClass : IntermediateClass
    {
        public override void InvokeMethod()
        {
            Console.WriteLine("This is the top method");
        }

        public void SomeJob()
        {
            // let's do some job here
            Console.WriteLine("Some job from Top class level");
            IntermediateMethod();
        }
    }

C# result
This is the base method
This is the intermediate method
Some job from Top class level
Some job from Intermediate class level
This is the top method

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s