C# Inheritance

C# Code Snippets Inheritance
Share:

About

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.

Code:

using System;

namespace Inheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            MyParentClass MPC = new MyParentClass();
            MyChildClass MCC = new MyChildClass();

            //Even though not included in the MyChildClass, MyFirstProperty can be accessed because it's inherited from the parent class.
            MCC.MyFirstProperty = 0;

            Console.WriteLine(MCC.MyFirstProperty);

            Console.ReadLine();
        }
    }

    //Example 1////////////////////////////////////////////////////////////////////////////////////////////

    class MyParentClass
    {
        public int MyFirstProperty { get; set; }
        public int MySecondProperty { get; set; }
    }

    //MyChildClass inherits the members of MyParentClass.
    class MyChildClass : MyParentClass
    {

    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////

    //Example 2///////////////////////////////////////////////////////////////////////////////////////////

    class Fruit
    {
        public int price { get; set; }
    }

    class Banana : Fruit
    {

    }

    class Grape : Fruit
    {
        public string color { get; set; }
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

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