65.9K
CodeProject is changing. Read more.
Home

Use Collection Object Initializers to Add Items

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (4 votes)

Apr 28, 2011

CPOL
viewsIcon

19782

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:
// 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:
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 :)