Comparing "override" and "new" in C#

gpeipman
35.5K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Welcome!

This example explains members versioning in C#. Members that support versioning are marked as virtual and therefore they can be overriden. From extended class it is possible to call member with same name in base class and this means that we have more than one version on given member.

Let's take a look at the following code sample where Animal, Dog, Kangaroo and Cat classes are defined.

Calling base version

Let's rewrite the code above to be more realistic and let's assume that most of animals run by default and those who don't will override the move method. Cat class calls the same base class method as Dog class does but it has local version of Move() method too.

Hiding original member

It is also possible to hide existing versions behind new ones. Take a look at LazyCat class in following example. It uses "new" keyword to define local version of Move() method. How it is different from overridden one? Run the code sample and see what happens with LazyCat when it is casted to Cat.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content