Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Use Collection Object Initializers to Add Items

0.00/5 (No votes)
29 Apr 2011 1  
Use of Collection Object initializers instead of adding into a collection explicitly
Problem: If we wanted to create a list which contains a collection of strings, we need to do something like this with C# 2.0:

XML
// Creating collection of string
     List<string> stringCollection = new List<string>();
     stringCollection.Add("The");
     stringCollection.Add("Code");
     stringCollection.Add("Project");


Solution: Now in C# 3.0, we do in the following way:

XML
IEnumerable<string> stringCollections = new List<string>
     {
          "The",
          "Code",
          "Project"
     };


This isn't a revolutionary idea, but I think it's very useful, simple and it costs less performance hits than the old one.

I advise to use the latest one.

Thanks :)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here