Frage

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

War es hilfreich?

Lösung

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

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

Andere Tipps

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() };
var list = new List<IMyCustomType>{ new MyCustomTypeOne(), new  MyCustomTypeTwo() };
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top