Classes

C# Inheritance

Class Inheritance

C# inheritance uses : for base class extension.

Introduction to Inheritance

Inheritance is a fundamental concept in object-oriented programming, allowing a class to inherit characteristics (fields and methods) from another class. In C#, inheritance is achieved using the : symbol. This not only promotes code reusability but also helps in establishing a hierarchy between classes.

Implementing Inheritance in C#

To implement inheritance in C#, you define a base class (also known as a parent class) and a derived class (also known as a child class). The derived class inherits the properties and methods of the base class. Here's a basic example:

Advantages of Using Inheritance

Inheritance provides several benefits in software development:

  • Code Reusability: You can reuse existing code, reducing redundancy.
  • Extensibility: Extend the functionalities of existing classes without modifying them.
  • Polymorphism: Implement polymorphic behavior by overriding base class methods in derived classes.

Overriding Methods

In C#, derived classes can modify or extend the behavior of methods inherited from base classes using method overriding. This is achieved using the override keyword. Here's how it works:

Access Modifiers and Inheritance

Access modifiers play an important role in inheritance. In C#, the public, protected, and private keywords control the accessibility of class members. Here's a quick rundown:

  • Public: Members are accessible from any code in the project.
  • Protected: Members are accessible within the same class and by derived classes.
  • Private: Members are accessible only within the same class.

Sealing Classes

In some cases, you might want to prevent a class from being inherited. This can be achieved using the sealed keyword. A sealed class cannot be used as a base class. Here's an example:

Previous
Interfaces