Search code examples
c#referenceparent

References between objects


I have been trying to figure this out for days.

What I have is three classes, let's call them City, House, Room:

class City
{
    List<House> Houses { get; set; }
    string Name { get; set; }
}

class House
{
    List<Room> Rooms { get; set; }
    string Name { get; set; }
}

class Room
{
    string Name { get; set; }
}

So, here we have a city, which holds a lot of houses. And the houses holds rooms.

Let's say for instance I get a room object, which has a name (and is grouped in the whole system with City->House->Room)

How would I be able to reference the City-objects Name variable from that Room object I have?

Like some magic way of doing "Room.House.City.Name"

I really hope you understand what I'm trying to ask, it's been driving me crazy for the last couple of days.


Solution

  • You can add a House property to your room and City property to your House like this:

    class House
    {
        List<Room> Rooms { get; set; }
        string Name { get; set; }
        public City City { get; set; }
     }
    
    class Room
    {
        string Name { get; set; }
        public House House { get; set; }
    }
    

    And when you are adding some house and room for example:

        City myCity = new City();
        House myHouse = new House { City = myCity, Name = "myHome" };
        Room myRoom = new Room { House = myHouse, Name = "myRoom" };
        myHouse.Rooms = new List<Room>();    
        myHouse.Rooms.Add(myRoom);
        myCity.Houses = new List<House>();        
        myCity.Houses.Add(myHouse);
        // here you can use:
        myRoom.House.City.Name
    

    But this is not so elegant and it's hard to add new Houses and Rooms.Additionally I would add some methods to make it easy for example in House class:

    class House 
    {
         public void AddRoom(Room room)
         {
            room.House = this;
            if (Rooms == null)
                Rooms = new List<Room>();
            Rooms.Add(room);
         }
    }
    

    And then I don't need to define a Room like this:

    Room myRoom = new Room { House = myHouse, Name = "myRoom" };
    

    Instead:

    myHouse.AddRoom(new Room { Name = "myRoom" });