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

Advertisements

1 thought on “Method overriding in C# – part 1”

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