coder
coder

Reputation: 4313

How to have a parent property in C# class?

For example, in the following classes I need to have a Parent property in Cupboard and Shelf. How do I do it?

public class Room
{
    public List<Cupboard> Cupboards { get; set; }
}

public class Cupboard
{
    public Room Parent 
    {
        get
        {

        }
    }
    public List<Shelf> Shelves { get; set; }
}

public class Shelf
{

}

Upvotes: 5

Views: 6187

Answers (1)

Mark Byers
Mark Byers

Reputation: 838796

You can use an automatically implemented property:

public class Cupboard
{
    public Room Parent { get; set; }
}

You can also choose to make the setter private and set it in the constructor.

public class Cupboard
{
    public Cupboard(Room parent)
    {
        this.Parent = parent;
    }

    public Room Parent { get; private set; }
}

Usage:

Room room = new Room();
Cupboard cupboard = new Cupboard(room);
Console.WriteLine(cupboard.Parent.ToString());

If you have many objects that all have a parent room you might want to create an interface so that you can find out which room is an object's parent without having to know its specific type.

interface IRoomObject
{
    Room { get; }
}

public class Cupboard : IRoomObject
{
    // ...
}

Upvotes: 6

Related Questions