Paul Kent

.NET Developer (AngularJS, jQuery, C#, Dependency Injection, Unit Testing, Onion Architecture, Azure Cloud)

What do the C# keywords virtual, override and new mean?

What does the virtual keyword in C# do? Let's look at a practical example below in .NET Fiddle:

Here we have two classes: Car and Ford. Ford inherits from Car. The Car class has two methods Move() and Stop(). The Move() method in the Car class is declared virtual. In the Move() method in the Ford class we've declared that method with the override keyword.

On line 7 we are creating an instance of Ford but using polymorphism we can store it as a Car object because Ford inherits from Car. On line 8 in our code, when we call the Move() method on the car, the Move() method on the Ford class is still being called as can be seen from the resulting output. You can't call the Car's Move() method outside of the Car or Ford class. Only the Ford's Move() method is called. This is what the virtual and override keywords in C# provide for us.

The Microsoft documentation on the virtual keyword describes the behaviour as of it follows:

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

Let's now have a look at the new keyword. The new keyword in C# has two usages. One is to instantiate a class, the other is to hide an inherited method, like what we are doing on line 34.

The Stop() method in the Car class is not declared as virtual which is in contrast to the Move() method. On line 9 when we call car.Stop() notice how the Stop() method on the base method is called and not the Ford's Stop() method.

I hope this gives a general idea of these three keywords (virtual, override and new) and how behave in the context of inheritance and polymorphism.

Comments are closed