C#C
C#2y ago
17 replies
danyule

Aggregation vs Composition (UML)?

Hi there, I'm struggling to understand the difference between the terms composition and aggregation from UML in the context of C#? How would you implement a composite and how would that differ from aggregation? My understanding, based on what I've read, is that composites manage their components entire lifecycle. So would you typically implement a composite using private classes? For example as follows:

Composition
public class Car
{
    private Engine _engine;

    public Car()
    {
        _engine = new Engine();
    }

    private class Engine
    {

    }
}


I understand you can argue an engine can exist independently of a car, but for the purposes of this question, assume that it doesn't. The same example using aggregation would look something like this:

Aggregation
public class Car
{
    private Engine _engine;

    public Car(Engine engine)
    {
        _engine = engine;
    }
}

public class Engine
{

}


I also have seen in the wild that both examples would be referred to as composition. So I'm a bit confused right now.
Was this page helpful?