Reputation: 340
I want to create a parent class that contains a list and can do simple operations on that list (add, remove, or swap items). The type of object in the list will be different for each child class. If I make it a List<object>
then I think I will have to do a bunch of casting in the child class (something that would be nice to avoid). Is there any way to accomplish this?
public abstract class Parent {
protected List<T> ListOfSomeType; // <- List<T> isn't allowed
protected void RemoveThing<T> (T thing) {
ListOfSomeType.Remove(thing)
}
protected void AddThing<T> (T thing) {
ListOfSomeType.Add(thing);
}
protected void SwapThings(int index1, int index2) {
var temp = ListOfSomeType[index1];
ListOfSomeType[index1] = ListOfSomeType[index2]
ListOfSomeType[index2] = temp;
}
}
public class Child1 : Parent {
public Child() {
ListOfSomeType = new List<SomeType>();
}
}
public class Child2 : Parent { // same sort of deal with new List<SomeOtherType>()}
Upvotes: 1
Views: 542
Reputation: 37050
If you promote the type T
to the class, then it can be used by the class members:
public abstract class Parent<T>
{
protected List<T> ListOfSomeType = new List<T>();
protected void RemoveThing(T thing)
{
ListOfSomeType.Remove(thing);
}
protected void AddThing(T thing)
{
ListOfSomeType.Add(thing);
}
protected void SwapThings(int index1, int index2)
{
var temp = ListOfSomeType[index1];
ListOfSomeType[index1] = ListOfSomeType[index2];
ListOfSomeType[index2] = temp;
}
}
Then when creating Child
, you specify the SomeType
type when you define the Parent
that it derives from:
public class Child : Parent<SomeType>
{
public Child()
{
ListOfSomeType = new List<SomeType>();
}
}
Upvotes: 3