Inheritance and Composition are two ways to create a relationship between classes and objects in Object-Oriented Programming Languages. In this article we are going to understand how we can use it and when we should use Inheritance or Composition

Inheritance

Inheritance it’s a principle of the Object-oriented programming that allow the classes to share attributes and methods beyond ‘Inheritance’. This is useful to reuse code or behaviour. In .NET it’s not allowed to have multiple inheritance, so you can only inheritance from one class.

This is a definition of Inheritance from the Microsoft documentation:

Inheritance is one of the fundamental attributes of object-oriented programming. It allows you to define a child class that reuses (inherits), extends, or modifies the behavior of a parent class

In Inheritance, we have two types of classes, the Base class and theDerived class. The Base class is the class that give the characteristics to the other class. The **Derived class **is the class that inherited the characteristics from the base class.

Let’s see an example of Inheritance in a real-world scenario using C#. I have this class that is named as Entity. This is a generic class that has two properties, an Id and the date on which the entity was created. Every class that inherited from Entity, will also have access to this two properties. This is an abstract class because this class cannot be instantiated, it only can be inherited.

namespace BookStore.Domain.Models
	{
	    public abstract class Entity
	    {
	        public int Id { get; set; }
	        public DateTime CreatedDate { get; set; }
	    }
	}

#dotnet #oop #dotnet-core #csharp #dot-net-framework

Inheritance and Composition
6.60 GEEK