Composition vs. inheritance in OOP and C#



Two of the important thing ideas in object-oriented programming (OOP) are inheritance and composition. Whereas each will help you reuse code, there are key variations between them. Inheritance establishes widespread conduct and interfaces in your courses, whereas composition combines and reuses current courses to create extra complicated objects.

On this article, we’ll dive into these two ideas of OOP and perceive when, why, and how one can use them in our .NET functions. To work with the code examples offered on this article, you need to have Visible Studio 2022 put in in your system. If you happen to don’t have already got a duplicate, you may obtain Visible Studio 2022 right here.

Create a console software mission in Visible Studio

First off, let’s create a .NET Core console software mission in Visible Studio. Assuming Visible Studio 2022 is put in in your system, observe the steps outlined beneath to create a brand new .NET Core console software mission in Visible Studio.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new mission.”
  3. Within the “Create new mission” window, choose “Console App (.NET Core)” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new mission” window proven subsequent, specify the title and site for the brand new mission.
  6. Click on Subsequent
  7. Within the “Further data” window proven subsequent, select “.NET 7.0 (Commonplace Time period Assist)” because the Framework model you wish to use.
  8. Click on Create.

We’ll use this mission to work with the examples of inheritance and composition within the subsequent sections of this text.

Reusability in object-oriented programming

Because the daybreak of laptop programming, completely different programming challenges have spawned completely different approaches, paradigms, and architectural types. One paradigm that has been round for many years is object-oriented programming. The OOP paradigm gives a number of advantages together with maintainability, extensibility, and code reuse.

One of many key advantages of OOP is code reusability. You’ll be able to obtain this in two other ways, both by inheritance (is-a relationship) or by composition (has-a relationship). The ideas of composition and inheritance are each elementary to OOP, however their approaches and implications are completely different.

The talk over the selection between composition and inheritance is many years outdated. Composition is normally most well-liked over inheritance for a number of causes, however you need to know the benefits and downsides of each earlier than deciding.

What’s inheritance in OOP? Why must you use it?

In inheritance, a category inherits properties and behaviors from one other class, apart from these which are non-public. The inheritance relationship between courses is described as an “is a” relationship (a buyer is a individual), the place a subclass is taken into account a specialised model of its superclass.

Using inheritance facilitates code reuse as a result of base courses outline widespread strategies that may be prolonged or changed by derived courses. Objects of various derived varieties could be dealt with interchangeably by their widespread superclass due to their hierarchical construction and polymorphism.

Inheritance gives a number of benefits:

  • Inheritance promotes extensibility by permitting you to create base courses that comprise widespread features that derived courses ought to inherit.
  • Inheritance helps you map real-world objects and their relationships into summary varieties.
  • Inheritance minimizes code redundancy and lowers improvement and upkeep prices as a result of you may reuse current code.
  • Inheritance ensures that subclasses observe a regular interface.

Nonetheless, inheritance additionally has disadvantages:

  • Inheritance will increase the coupling between a base kind and its derived varieties. If you happen to change your base class, all subclasses are additionally affected.
  • Inheritance breaks encapsulation as a result of the strategies and attributes of the bottom are uncovered to its derived courses

Use inheritance in OOP and C#

To implement inheritance in C#, you need to use the extends key phrase as proven within the code snippet given beneath.

public class Particular person
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Handle { get; set; }
    public string Metropolis { get; set; }
    public string PostalCode { get; set; }
    public string Nation { get; set; }
public class Buyer: Particular person
    //Write the members of the client class right here
public class Provider : Particular person
    //Write the members of the provider class right here

What’s composition in OOP? Why must you use it?

Composition is a mechanism that enables an occasion or object of a category to comprise cases of the identical or different courses. It establishes a “has a” relationship between courses (an writer has a guide), the place one class accommodates an object of one other class.

Composition combines current courses to create extra complicated courses, which promotes code reuse. As a result of objects could be dynamically composed at runtime and simply changed or modified with out affecting the complete system, composition permits for better flexibility and modularity.

Use composition in OOPS and C#

The next code snippet illustrates how one can implement composition in C#.

public class E book
    public int Id { get; set; }
    public string Title { get; set; }
public class Writer
    protected Listing<E book> books = new Listing<E book>();
    //Different members

Why desire composition over inheritance?

Once you design a base class from which a number of courses will inherit properties and behaviors, you present a standard interface for the subclasses. Nonetheless, these advantages come at the price of quite a lot of unfavourable results:

  • All subclasses of the bottom class shall be pressured to stick to the implementations of the interface.
  • The implementation of the bottom class could turn out to be troublesome to vary over time.
  • The tight coupling between the bottom class and all its subclasses could hinder improvement.

There are methods to unravel these issues akin to by utilizing the SOLID rules of object-oriented programming. Nonetheless, doing so can overcomplicate your design and sort hierarchy. A greater different is changing inheritance with composition except there’s a particular purpose to make use of inheritance.

Usually, you need to desire utilizing composition over inheritance as a result of it can make your supply code much less tightly coupled. Nonetheless, to say you need to at all times favor composition over inheritance could be an oversimplification. Simply bear in mind the “is a” and “has a” rule when designing your varieties.

Want utilizing composition over inheritance when it’s essential to reuse code and the categories don’t have an “is a” relationship. Moreover, in case your varieties don’t have an “is a” relationship however you want polymorphism, use composition with interfaces.

As a rule, you need to resolve whether or not composition or inheritance is extra appropriate in your wants based mostly on the particular necessities. A good selection is to mix composition and inheritance when growing methods to get one of the best of each worlds. Finally, the choice between composition and inheritance will depend upon the kind of software you’re constructing, the relationships between the courses, and the options you need.

Copyright © 2023 IDG Communications, Inc.