Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a List and populate with values using one code statement [closed]

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

like image 381
user1765862 Avatar asked May 23 '13 10:05

user1765862


4 Answers

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

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

like image 88
Colm Prunty Avatar answered Oct 21 '22 08:10

Colm Prunty


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

Not quite sure why you want it in one line?

like image 31
nik0lai Avatar answered Oct 21 '22 07:10

nik0lai


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},
}
like image 20
Atish Dipongkor Avatar answered Oct 21 '22 09:10

Atish Dipongkor


You can use a collection initializor:

var list = new List<IMyCustomType>() { new MyCustomTypeOne(), new MyCustomTypeTwo(), new MyCustomTypeThree() };
like image 44
David Hoerster Avatar answered Oct 21 '22 07:10

David Hoerster