Inheritance in C#

Inheritance

Today we learn how to do inheritance in C#. In programming when a class uses objects and properties of another class then it is known as inheritance. So today we will cover following topics.

  • How to create a class.
  • How to create a super and sub class.
  • Access base class from derived class.
  • Inherit child class from base class.
  • How to protect base class properties.

So first as we now C# is a pure object oriented language and it uses classes to execute a function and to understand the concept of inheritance we must have to know how to create a class in C#.

Code:

Above is the class name city having one attribute and one function or method. Now let’s take an example how to create a super and sub class.

Example of Inheritance in C#:

To access base class in child class we must have to make sure that the variable or method we want to access is public or protected, and then we simply call this as we call members of the same class.

To inherit child class from super class “:” colon is used.

Like

public class derived : public base{ }

To protect base class function and attributes we have to define their scope to private so that they are not visible outside the class even to that one which inherits that class and this process is called encapsulation.

To learn more about inheritance and its types

How derived Class access Base Class and how to handle constructors?