How to maintain aggregation and composition in C #?

Aggregation : the lifetime of the contained object is independent of the container object

Composition : the lifetime of the contained object is similar to the container object.

In C ++, this can be done using new and delete statements. Since C # does not provide a delete operator, how can we achieve aggregation and composition in C #?

+4
source share
4 answers

Life expectancy depends on ownership, but ownership is a key idea in distinguishing between aggregation and composition. As part of the dependent object, it belongs entirely to the container. The implication for this in C ++ is that the container must take care of its destruction in order to avoid memory leak. In C #, it depends on the type of object / memory (managed or unmanaged); the container must implement IDisposable and clear unmanaged, compositional objects. In both cases, the aggregates exist independently of the container and cannot be cleaned after.

0
source
+4
source

If both objects implement the IDisposable and Garbage collection, then the parent objects of the Dispose method can call all child objects using the placement method. It gives you composition.

Then you can have methods for the parent that have the children, not the parent, i.e. aggregation.

+2
source

Paste IDisposable into your contained objects and call Dispose when you want to delete them.

+1
source

Source: https://habr.com/ru/post/1383425/


All Articles