views:

22

answers:

1

Hi There,

I am fairly new to OOP and wondered if you could provide some help on the best solution to the following.

public class GenericClass
{
    private List<GenericListItem> _listItems;
}

public class SpecificClass : GenericClass
{
    // I'd like to change the listItems specialisation to SpecificListItem (inherits from GenericListItem)
}

How would I be able to achieve the change in specialisation for the collection? Should I be creating a virtual method when adding to the collection and override to specify the correct type (SpecificListItem)? Then cast it to SpecificListItem when accessing it?

Please accept my apologies, this is my first post so it may be vague. If I need to give more information please let me know. Also, I'm sorry for my ignorance in this question!

Many Thanks,

Sam

+2  A: 

You may want to make GenericClass generic:

public class GenericClass<T> where T : GenericListItem
{
    private List<T> _listItems;
}

public class SpecificClass : GenericClass<SpecificListItem>
{
    // ...
}

That may or may not be appropriate - it really depends on what you want to do with the list, and what these classes are responsible for in the first place.

Jon Skeet
Thanks for the reply Jon, I have no concrete implementation to use this for and was really just "thinking out loud" but your reply is a great starting point for me.When I have a viable reason to do something like this I will expand my query otherwise it's 'welcome to the world of generics' for me!
Sammy T