15

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

Stéphane Gourichon
  • 6,493
  • 4
  • 37
  • 48
user1765862
  • 13,635
  • 28
  • 115
  • 220

5 Answers5

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

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

Colm Prunty
  • 1,595
  • 1
  • 11
  • 29
9
var list = new List<IMyCustomType>
{
   new MyCustomTypeOne(),
   new MyCustomTypeTwo(),
   new MyCustomTypeThree()
};

Not quite sure why you want it in one line?

nik0lai
  • 2,585
  • 23
  • 37
3

use the collection initialiser

var list = new List<IMyCustomType>
{
   new MyCustomTypeOne(){Properties should be given here},
   new MyCustomTypeTwo(){Properties should be given here},
   new MyCustomTypeThree(){Properties should be given here},
}
Atish Kumar Dipongkor
  • 10,220
  • 9
  • 49
  • 77
2

You can use a collection initializor:

var list = new List<IMyCustomType>() { new MyCustomTypeOne(), new MyCustomTypeTwo(), new MyCustomTypeThree() };
David Hoerster
  • 28,421
  • 8
  • 67
  • 102
0
var list = new List<IMyCustomType>{ new MyCustomTypeOne(), new  MyCustomTypeTwo() };
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162