We\'re creating an object hierarchy where each item has a collection of other items, and each item also has a Parent
property pointing to its parent item. Pretty st
The only two things I can think of:
One:
Use sort of option number 2 you mention above (which I do constantly myself)...but make the implementation of the interface (Item) be a nested private class inside of ItemsCollection
... that way only ItemsCollection
knows about the setter. The interface IItem
only declares a getter for Parent...and no one can cast it to Item because Item is private to ItemsCollection
. So, something like:
public class ItemsCollection : ObservableCollection
{
private class Item : IItem
{
public object Parent { get; set; }
}
private CheckParent(IItem item)
{
if(item.Parent != null) throw new Exception("Item already belongs to another ItemsCollection");
((Item)item).Parent = this.Owner; // <-- This is where we need to access the private Parent setter
}
public static IItem CreateItem() { return new Item(); }
}
public interface IItem
{
object Parent {get; }
}
and when you want ItemsCollection
to set the item Parent, case the IItem
instance to Item (which does expose a setter). Only ItemsCollection
can do this cast, since the Item implementation is private to ItemsCollection
...so I think that accomplishes what you want.
Two:
Make it internal not private...you don't get exactly what you want, but you can use InternalsVisibleToAttribute
to denote that the internal members are visible to another assembly.