Search code examples
c#.netlistinitializer

Declare a List and populate with values using one code statement


I have following code

var list = new List<IMyCustomType>();
list.Add(new MyCustomTypeOne());
list.Add(new MyCustomTypeTwo());
list.Add(new MyCustomTypeThree());

this of course works, but I'm wondering: how can I declare the list and populate it with values using one statement?

Thanks


Solution

  • var list = new List<IMyCustomType>{ 
        new MyCustomTypeOne(), 
        new MyCustomTypeTwo(), 
        new MyCustomTypeThree() 
    };
    

    Edit: Asker changed "one line" to "one statement", and this looks nicer.