DEV Community

Milecia
Milecia

Posted on • Updated on

The Override Keyword

It's always good to understand the basic things in web development. With that being said, what do you know about the override modifier? Sometimes it's so easy to use and not think about that you forget what it is.

Well, the override keyword is used to give a new implementation of a method inherited from a base class. If you need a quick refresher on inheritance, you can check it out here. The base method has to be virtual or abstract to be overridden and the inherited method has to use the same name as the base method. They must also have the same access level modifier to make sure they work correctly. So if one is public the other has to be public as well.

The override keyword also makes sure any objects derived from the inherited class use the inherited class's implementation of any methods instead of the base class implementation. Here's a little illustration of what that looks like:

override.jpg

Override methods can't be modified by using new, static, or virtual modifiers so there's that. Really the override keyword is as simple as it is easy to use. You just have to pay attention to when you need to use it. Pretty much anytime you have an base method that has an abstract or virtual modifier then you can expect to override it when you inherit it.

By default, C# methods aren't virtual or abstract so you don't have to worry about using override on every method you inherit. That makes it easier to work with multiple methods in a base class that will be inherited by different derived classes. You only have to implement the methods you made virtual or abstract.

Sometimes it's good to see these things in a form other than code. It could be that last little piece before that "a-ha" moment comes. I hope that this helped you understand how the override modifier works! It just takes some time to remember which methods you modified but once you have that down, you're good to go.


Hey! You should follow me on Twitter because reasons: https://twitter.com/FlippedCoding

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.