C# Inheritance

C# Code Snippets Inheritance


In this code snippet, we will take a look at the base keyword in C#.

Inheritance means that one class can inherit members from another class. This is one of the fundamental concepts in OOP(object-oriented programming).  (see example 1)

Let’s say we are making an app for a store. The store sells grapes and bananas. Both items will have a price so we can make a parent class called fruit and put the price property inside. Then the banana and grape classes would inherit the price from the fruit parent class. Grapes can also have a color(white or red). This color property would only be put in the grape class. (see example 2)

Inheritance reduces code duplication and it provides organization and structure to the code. Despite how crucial inheritance is to OOP don’t go overboard with it and only use it when it makes sense to do so. 

Note: A child class can only have one parent. If you have the need for more than one parent use an interface instead.

Let’s have a look at the code below to see how to use inheritance.


Resulting output:


Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger