0

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?

4
  • You have second BaseEntity class defined within the BaseEntity class? I don't think that's even possible. EDIT I think you meant that to be the constructor, right? Commented Jun 30, 2012 at 22:32
  • 1
    @Kevin: I assume that it's a typo, omit the class and you get a constructor. Commented Jun 30, 2012 at 22:34
  • @Kevin: Yes. Sorry! I was typing a simpler example looking at my IDE. Edited the question now. Commented Jun 30, 2012 at 22:35
  • How do your KeyValuePair classes differ? If they are all related in some way, could you not use a generic type parameter? Commented Jun 30, 2012 at 22:36

1 Answer 1

4

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) { }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Awesome. Thank you. I was moving towards that approach after I found this: stackoverflow.com/questions/12051/… and now I have your answer as well. Thank you for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.