I have a class Container
containing objects of type Item
. They are different classes, and especially they have no common base class (e.g. a Container
does not itself have a Container
).:
class Container
{
public ICollection<Item> Items { get { /* ... */ } }
}
class Item
{
public Container Container { get { /* ... */ } }
}
I’d like to enforce that each Item
needs to have exactly one Container
, and I’d like to make sure there never can be an inconsistent situation such that e.g. i.Container.Items.Contains(i)
returns false.
This could be done by e.g. adding a method Container.AddItem
that sets the Item
’s Container
property accordingly or by having a Item.SetContainer
method that takes care of Container.Items
.
Example:
class Item
{
private Container container;
public Container Container
{
get
{
return container;
}
set
{
if (container != null)
container.Items.Remove(this);
container = value;
if (value != null)
value.Items.Add(this);
}
}
}
This could be easily done with the concept of a “friend”, but I’m using C# that does not have friends, and thus this example code won’t compile. However, it of course would compile if Container.Items
had a public setter, but this again would allow inconsistencies: A “user” of the classes would need to know not to use the setter of Container.Items
, but Item.Container
instead.
After searching for quite some time, I feel there is no way to enforce this restriction that seems to be so trivial. (Using internal
might be a work-around, but no solution.)
Is there an elegant way to enforce this one-container-per-item rule without the concept of “friend”?
i.Container == c
and!c.Items.Contains(i)
. So, yes, one solution (that is not possible without friends) is that onlyContainer
has write access toItem.Container
Item
sContainer
.