Inheritance is one of the fundamental concepts of object-oriented programming. In C#, inheritance is a mechanism that allows a class to inherit properties and methods from another class. In this article, we will discuss inheritance in C# and its significance in programming.
What is Inheritance in C#?
Inheritance is a way to create a new class that is a modified version of an existing class. The new class, called a derived class, inherits the properties and methods of the existing class, called a base class. The derived class can also add new properties and methods or modify the existing ones.
Inheritance is useful because it allows you to create a hierarchy of classes that share common properties and methods. The base class contains the common properties and methods, and the derived classes can specialize or add to those properties and methods.
In C#, inheritance is achieved using the “extends” keyword. For example, to create a derived class called “Employee” that inherits from a base class called “Person”, you would write the following code:
protected string Name;
protected int Age;
class Employee : Person
private int EmployeeID;
In the above code, the “Employee” class inherits from the “Person” class. The “Employee” class has a private field called “EmployeeID” in addition to the properties of the “Person” class.
Types of Inheritance in C#
In C#, there are five types of inheritance:
- Single Inheritance – A derived class can inherit from only one base class.
- Multilevel Inheritance – A derived class can inherit from a base class, which itself inherits from another base class.
- Hierarchical Inheritance – Several derived classes can inherit from the same base class.
- Multiple Inheritance – A derived class can inherit from multiple base classes. However, C# does not support multiple inheritance of classes, but it can be achieved using interfaces.
- Hybrid Inheritance – A combination of two or more types of inheritance.
Access Modifiers in Inheritance
Access modifiers are used to control the accessibility of properties and methods in a class. In C#, there are four access modifiers: public, protected, internal, and private.
When a derived class inherits from a base class, it can access the public and protected members of the base class. Private members of the base class are not accessible in the derived class. If a member in the base class has internal access modifier, it is accessible only within the same assembly, and it’s not accessible in derived classes outside of the assembly.
Inheritance is a powerful concept in object-oriented programming, and it allows you to create a hierarchy of classes that share common properties and methods. C# provides various types of inheritance, and access modifiers allow you to control the accessibility of properties and methods in a class hierarchy. Understanding inheritance is crucial for writing efficient and reliable code in C#