Declare a List and populate with values using one code statement

user1765862 picture user1765862 · May 23, 2013 · Viewed 28.2k times · Source

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

Answer

Colm Prunty picture Colm Prunty · May 23, 2013
var list = new List<IMyCustomType>{ 
    new MyCustomTypeOne(), 
    new MyCustomTypeTwo(), 
    new MyCustomTypeThree() 
};

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