Pergunta

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

Foi útil?

Solução

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

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

Outras dicas

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() };
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top