1

I am new to inherit from list concept and I have a little confusion of initializing that.

Here is a simple example of my real code, here is my class that inherits from list:

public class List_Of_Int : List<int>
{
    public string key{get; set;}
    public List_Of_Int(string key)
    {
        this.key = key;
    }
}

and here is where I need to initialize my variable:

    List<int> list_of_int = new List<int>() { 1, 2, 3 };
    List_Of_Int list_of_list = new List_Of_Int("some_key") **Some Code**

I want to assign list_of_int to my list_of_list, I believe there's a code replace some code that will do that, Is it true?

I know I can add by using AddRange(list_of_int ) later but I'm just wondering if I can do it while declaration?

3
  • 8
    stackoverflow.com/questions/21692193/why-not-inherit-from-listt Commented Nov 12, 2018 at 14:13
  • 1
    That code makes no sense. You have a list of entegers and want to initliazie it with a string? Or just add a random property into the new class, with no relations to the list itself? I do agree that it sounds like you should create a class containing a list, rather then inheriting from list. Commented Nov 12, 2018 at 14:14
  • Look at the other constructors of List. You are missing the one that takes the IEnumerable. Commented Nov 12, 2018 at 14:16

1 Answer 1

1

Just wondering what you are asking actually but I guess this is what probably you are looking at

public class List_Of_Int
{
    public List<int> key {get; set;}
    public List_Of_Int(List<int> key)
    {
        this.key = key;
    }
}

You can now initialize like

List<int> list_of_int = new List<int>() { 1, 2, 3 };
List_Of_Int list_of_list = new List_Of_Int(list_of_int) 
Sign up to request clarification or add additional context in comments.

1 Comment

This highlights exactly why you should Prefer composition over inheritance?

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.