Reputation: 29209
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?
Upvotes: 3
Views: 122
Reputation: 70776
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)
Upvotes: 2
Reputation: 3117
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.
Upvotes: 0
Reputation: 31196
Like this
class HeaderA : Header<ItemB> { .... }
class HeaderB : Header<ItemA> { .... }
Upvotes: 1
Reputation: 87308
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 { }
Upvotes: 6