Method overriding in C# – part 2

As shown in the previous example a new keyword doesn’t guarantee that invoking of a method which is implemented in derived class will be possible, when reference is type of base class. To resolve this problem override keyword can be used.

C# code

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

            Console.ReadLine();
        }
    }

    public class BaseClass
    {
        public virtual void DisplayMessage()
        {
            Console.WriteLine("Base class message");
        }
    }

    public class DerivedClass : BaseClass
    {
        public override void DisplayMessage()
        {
            Console.WriteLine("Derived class message");
        }
    }

    public class DerivedClassTwo : DerivedClass
    {
        public override void DisplayMessage()
        {
            Console.WriteLine("Derived class two message");
        }
    }

C# result
Derived class two message

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