GarXik
GarXik

Reputation: 37

Is this example of a composition relationship correct?

public class House
{
        private Person owner;
        private List<Room> rooms;

        public House(Person _owner)
        {
            this.owner = _owner;
            this.rooms = new List<Room>();
        }

        public void AddRoom(Room r)
        {
            rooms.Add(r);
        }
}

I have this class, am I correct in saying there's a composition relationship between the House Class and the Room Class since if you destroy an instance of house the list of rooms is deleted with it?

Upvotes: 0

Views: 94

Answers (2)

JonasH
JonasH

Reputation: 36556

While this is an example of composition, I find many examples of both composition and inheritance to be rather artificial.

Since the house is the only object to reference the room list, when the house is eligible for collection, the room list would also be so. The same might not be true for the owner, or the rooms, since the owner or rooms might have been added to other houses. Note that in c# and .Net we usually do not use the term "destroy", since the Garbage collector is responsible reclaiming memory, and we use the disposable/finalizer patterns to ensure other kinds of resources are reclaimed.

My preferred example of composition/inheritance would be geometry. A Square has four corners. A square is a rectangle (at least if it is immutable). This has direct application in many programs, so actually provides a useful abstraction.

I would recommend reading Eric Lipperts Wizards and Warriors for more about object orientation.

Upvotes: 1

Paul Alan Taylor
Paul Alan Taylor

Reputation: 10680

This is an instance of composition. You're making one class using other classes.

However, your question is veers into garbage collection.

Will the contents of the Rooms property be deleted when the instance of House is destroyed? Yes. Eventually. When the garbage collector gets around to it. It may not disappear at the exact instant you think it does.

You can have greater control over the lifetime of things on the heap with deterministic finalization (mostly implemented through the using block, but you can also create explicit dispose methods).

Sorry for the long explanation here, but felt like you were asking two questions so decided to answer both - and didn't want a link-only answer.

https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals

https://www.oreilly.com/library/view/programming-net-components/0596102070/ch04s05.html

Upvotes: 1

Related Questions