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
var list = new List<IMyCustomType>{
new MyCustomTypeOne(),
new MyCustomTypeTwo(),
new MyCustomTypeThree()
};
Edit: Asker changed "one line" to "one statement", and this looks nicer.
var list = new List<IMyCustomType>
{
new MyCustomTypeOne(),
new MyCustomTypeTwo(),
new MyCustomTypeThree()
};
Not quite sure why you want it in one line?
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},
}
You can use a collection initializor:
var list = new List<IMyCustomType>() { new MyCustomTypeOne(), new MyCustomTypeTwo(), new MyCustomTypeThree() };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With