Legend
Legend

Reputation: 116800

How can I instantitate a list based on the specific object type?

I have the following definitions:

public class BaseEntity 
{
    ...
    public BaseEntity()
    {

    }
}

public class KeyValuePair
{
    public string key;
    public string value;
    public string meta;
}

public class KeyValuePairList : BaseEntity
{
    public List<KeyValuePair> List {set; get;}

    public KeyValuePairList(IEnumerable<KeyValuePair> list)
    {
        this.List = new List<KeyValuePair>();
        foreach (KeyValuePair k in list) {
            this.List.Add(k);
        }
    }
}

I have 10 more different classes like KeyValuePair and KeyValuePairList all achieving the same purpose - the former defines the object, the latter defines the list into which these objects should be placed. How can I incorporate this functionality into the base class BaseEntity so that I don't have to redefine the List instantiation logic in each individual class i.e. I want to be able to instantiate the list based on the object type being passed to the constructor? Any suggestions?

Upvotes: 0

Views: 86

Answers (1)

Kevin Aenmey
Kevin Aenmey

Reputation: 13419

Can you use generics?

public class BaseEntity<T> where T: class
{
    public List<T> List { set; get; }

    public BaseEntity(IEnumerable<T> list)
    {
        this.List = new List<T>();
        foreach (T k in list)
        {
            this.List.Add(k);
        }
    }
}

public class KeyValuePair
{
    public string key;
    public string value;
    public string meta;
}

public class KeyValuePairList : BaseEntity<KeyValuePair>
{
    public KeyValuePairList(IEnumerable<KeyValuePair> list) 
        : base(list) { }
}

Upvotes: 4

Related Questions