I have the following class hierarchy.
class Header { IEnumerable<Item> Item { get; set; } .... }
class HeaderA : Header { .... } // Item should have the type of IEnumerable<ItemA>
class HeaderB : Header { .... } // Item should have the type of IEnumerable<ItemB>
class Item { .... }
class ItemA : Item { .... }
class ItemB : Item { .... }
Is it possible to have compile time checking on the type of Item
to make sure it's IEnumerable<ItemA>
, IEnumerable<ItemB>
for ItemA
and ItemB
respectively? Is there any better design?
You can change the definition of the Header class to pass the type parameter to it, then you could impose that:
class Header<TItem> where TItem : Item { IEnumerable<TItem> Item { get; set; } }
class HeaderA : Header<ItemA> { } // Item should have the type of IEnumerable<ItemA>
class HeaderB : Header<ItemB> { } // Item should have the type of IEnumerable<ItemB>
class Item { }
class ItemA : Item { }
class ItemB : Item { }
You should use a Generic Class
You can use a generic type and pass it to the class.
public class Header<T> where T : Item
{
IEnumerable<T> Item { get; set; }
}
Header<ItemA> AHeader;
Header<ItemB> BHeader;
http://msdn.microsoft.com/en-US/library/sz6zd40f(v=vs.100)
Like this
class HeaderA : Header<ItemB> { .... }
class HeaderB : Header<ItemA> { .... }
If I understand your question correctly, you can change the signatures of the Header class to accomplish this.
class Header<ItemType> { IEnumerable<ItemType> Item {get; set;} ....}
class HeaderA : Header<ItemA> { .... }
class HeaderB : Header<ItemB> { .... }
class Item { .... }
class ItemA : Item { .... }
class ItemB : Item { .... }
would result in HeaderA only allowing ItemA objects and HeaderB only allowing ItemB objects to be put into their respective Item collections.