m.edmondson
m.edmondson

Reputation: 30882

Concise way to initialise a collection

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<>)?

Upvotes: 1

Views: 581

Answers (4)

crypted
crypted

Reputation: 10306

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.

Upvotes: 0

Dan Puzey
Dan Puzey

Reputation: 34198

Yes:

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

Upvotes: 0

Jamie
Jamie

Reputation: 3931

Use a collection initializer

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

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

Upvotes: 0

Bala R
Bala R

Reputation: 108957

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}
                      };

Upvotes: 8

Related Questions