C # declare a list and populate with values ​​with a single line of code

I have the following list

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

this works, but I wonder how can I declare a list and populate the values ​​with a single statement?

thanks

+7
source share
5 answers
 var list = new List<IMyCustomType>{ new MyCustomTypeOne(), new MyCustomTypeTwo(), new MyCustomTypeThree() }; 

Edit: Asker changed “one line” to “one statement”, and it looks better.

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

Not quite sure why you want it on one line?

+8
source

use collection initializer

 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}, } 
+3
source

You can use the initializor collection :

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

All Articles