0

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?

Ahmed Salah
  • 851
  • 2
  • 10
  • 29
  • 8
    https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt – marsze Nov 12 '18 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. – Christopher Nov 12 '18 at 14:14
  • Look at the [other constructors](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.-ctor?view=netframework-4.7.2) of List. You are missing the one that takes the IEnumerable. – Hans Passant Nov 12 '18 at 14:16

1 Answers1

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) 
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • 2
    This highlights exactly why you should [Prefer composition over inheritance?](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) – Liam Nov 12 '18 at 14:19