Aggregation and Composition in C#

Hi Friends,

In Today’s discussion, we will discuss Aggregation and Composition in detail using C#. So, Let’s get started. Let me go ahead and create simple console App for demoing the same.

Then, I have also created two other dependent classes as shown below.

Once, the class gets created, It’s time to feed the value via constructor. Hence, below is the finished code for the same.

You will also notice that here, I have used Composition concept. Composition is tied with actual object which is patient here and hence DoctorInfo also got constructed.

Now, main program looks like

And, when i run the program, it will produce the following output.


However, I can modify the main program to add more info to this via aggregation as shown below.

With the above change in place, it will display the following info.


Therefore, in a nutshell, Aggregation is the stuff which can be added at later point of time to the object but, composition got constructed with object creation itself.

Rahul Sahay
Happy Coding

This entry was posted in C# and tagged . Bookmark the permalink.

3 thoughts on “Aggregation and Composition in C#

  1. You are confusing construction with composition and mutation with aggregation. Aggregation is composition. Specifically it is a flavor of composition where an object contains one or more aggregate properties. For example, a doctor object might contain a number of patient objects, perhaps stored in a list. It has absolutely nothing to do with the mechanics of when and how objects are instantiated.

    • Hi,

      Agree with you. But, this is a simple example around that. However, “Composition is the idea that objects are made up of or composed of other objects. These are intrinsic parts of the containing objects. Here, DoctorInfo is intrinsic to Patient. Which is called composition.

      Aggregation says objects can bring together separate objects that have their own lifetime. Like, a patient can have an insurance policy or cannot have. However, whenever a patient visits hospital, one doctor gets assigned to patient. Hence, while creating patient object, doctorInfo automatically came into picture. Here, lifetime of Patient object is directly dependent on DoctorInfo.

      But, in case of aggregation, it is not mandatory. we can bring these objects at any point of time.

Comments are closed.