Composition
In this lesson, you'll learn how to achieve composition in C#.
We'll cover the following
Composition
is the practice of accessing other class objects in your class. In such a scenario, the class which creates the object of the other class is known as the owner and is responsible for the lifetime of that owner object.
Composition relationships are Part-of relationships where the part must be a constituent of the whole object and cannot exist independently of the whole. We can achieve composition by adding the classes together like parts in another class to make a complex unit.
So, what makes the composition unique?
In composition, the lifetime of the owned object depends on the lifetime of the owner.
Example
For the sake of simplicity, let’s assume that a VendingMachine
is composed of a Display and KeyPad. In this case, a VendingMachine
owns these objects so it is an Owner class and Display
and KeyPad
classes are Owned classes.
Get hands-on with 1400+ tech skills courses.