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

Method overriding in C# – part 1

Take a look at the example below. It doesn’t matter if we use a new keyword or not. As you can see reference bc will invoke the method of the class that matches its type (in this case BaseClass).

C# code

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

        Console.ReadLine();
    }
}

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

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

C# result
Base class message