1

I can initialise a class in a concise manner using something like:

public static readonly type TYPE_NAME = new type() { ClientIp = "ClientIp", LanguageCode = "LanguageCode", SessionToken = "SessionToken", SystemKey = "SystemKey" }; 

However is it possible to initialise a collection in a similar way (inherited from List<>)?

1

4 Answers 4

8
List<string> strList = new List<string>{ "foo", "bar" }; List<Person> people = new List<Person>{ new Person { Name = "Pete", Age = 12}, new Person { Name = "Jim", Age = 15} }; 
Sign up to request clarification or add additional context in comments.

Comments

0

Use a collection initializer

http://msdn.microsoft.com/en-us/library/bb384062.aspx

List<int> list = new List<int> { 1, 2, 3 }; 

Comments

0

Yes:

var l = new List<int>() { 1, 1, 2, 3, 5 }; 

Comments

0

You can surely use collection initializer. To use this,

List<int> collection= List<int>{1,2,3,...}; 

To use collection initializer it need not to be exactly of List type. Collection initializer can be used on those types that implements IEnumerable and has one public Add method.

You use Collection initializer feature even in the following type.

public class SomeUnUsefulClass:IEnumerable { public IEnumerator GetEnumerator() { throw new NotImplementedException(); } public void Add(int i) { //It does not do anything. } } 

Like,

 SomeUnUsefulClass cls=new SomeUnUsefulClass(){1,2,3,4,5}; 

which is perfectly valid.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.