Inheritance in C# - CloudFronts

Inheritance in C#

Posted On February 15, 2023 by Sourav Patil Posted in  Tagged in ,

In C#, inheritance is a way to create a new class that is a modified version of an existing class. The new class is called the derived class, and the existing class is the base class.

The derived class inherits the base class members, which means it has access to all of the base class’s fields and methods. This is useful because it allows you to reuse code and avoid writing the same code over again in the derived class. To create a derived class in C#, you use the: operator, followed by the name of the base class. For example:

The derived class can then use the base class members as if they were it’s own. It can also override the base class’s methods or hide them with the new keyword.

In the example above, the derived class is overriding the Some Method method from the base class, which means that it is providing a new implementation for that method. The new keyword is used to hide the Some Other Method method from the base class, which means that the derived class provides its own version of the method that is separate from the one in the base class.

In addition to inheriting from a single base class, a class in C# can also implement one or more interfaces. An interface is a set of related methods that a class can implement. A class that implements an interface must provide an implementation for each of the methods in the interface.

In the example above, the derived class is both derived from the Base Class and implements the Isom Interface. This means that it has access to all of the members of the Base Class as well as the method defined in the Isom Interface.

In C#, inheritance is a powerful tool that allows you to create new classes based on existing ones. It helps you reuse code and avoid having to write the same code over again, saving time and making your code easier to maintain.


Share Story :

Secured By miniOrange