Christopher Pisz February 2016

base class collection defined by derived class

I'm not even close to as experienced in C# as I am in C++, but trying to get better.

In C#, does there exist a way to create a base class that contains a property which is a List and then in the derived class define what T is for that concrete type?

public class Base
{
    public List<T> Data { get; set; }
}

public class Derived : Base
{
    // Declare to the world you use Base.data<Elephant>
    // Callers of my Data property get Elephants
}

I imagine not, since you can no longer act on the interface in the base class since you wouldn't know what type you are getting until you know what type the actual instance is, but maybe there is some magical thing in C# that is similar to this?

Answers


Yacoub Massad February 2016

You can make the base class generic like this:

public class Base<T>
{
    public List<T> Data { get; set; }
}

And then when you create the derived class, you can specify T like this:

public class Derived : Base<Elephant>
{

}

For the consumers of Derived, the type of the Data property is List<Elephant>.

Post Status

Asked in February 2016
Viewed 2,345 times
Voted 7
Answered 1 times

Search




Leave an answer