Composition C# Example

R M Shahidul Islam Shahed
3 min readAug 29, 2023

Composition in object-oriented programming (OOP) refers to the concept of building complex objects by combining simpler or more focused objects, often referred to as components or parts. It allows you to create larger, more specialized objects by aggregating smaller, reusable building blocks.

Composition establishes a “has-a” relationship between the containing object (composite) and its components.

Composition C# Example

In composition, the containing object doesn’t inherit behavior or attributes from its components like it would in inheritance. Instead, it delegates tasks and responsibilities to its components, which encapsulate specific functionalities. This approach promotes code reuse, modularity, and maintainability while avoiding some of the issues associated with deep inheritance hierarchies.

Composition is a key concept in object-oriented programming that involves creating classes by combining existing classes as members rather than using inheritance. Here’s an example in C# that demonstrates composition:

💻 Engine Class

public class Engine
{
public void Start()
{
Console.WriteLine("Engine started");
}
}

💻 Wheel Class

public class Wheel
{
public void Rotate()
{
Console.WriteLine("Wheel…

--

--

No responses yet