Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Use Collection Object Initializers to Add Items

, 29 Apr 2011
Rate this:
Please Sign up or sign in to vote.
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 Smile | :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sanjay J Patolia
Software Developer Software Industry
India India
No Biography provided

Comments and Discussions

 
QuestionWhy should i use IEnumerable.. PinmemberV G S Naidu A28-Oct-12 23:38 
AnswerRe: Why should i use IEnumerable.. PinmemberSanjay J Patolia18-Feb-13 23:31 
GeneralRe: A method which accepts a list, can only accept a list, where... PinmemberPatolia Sanjay2-May-11 21:31 
Generalhow do i implement this in my own classes, so they would sup... Pinmembermastamac5-May-11 11:16 
GeneralYou are talking about static cases. This works only when you... Pinmemberben pour3-May-11 9:52 
Generalso which i should use in my code? Pinmemberspydeehunk2-May-11 22:47 
GeneralIList<string> namelist = new List<string> { "sunny","kumar",... Pinmemberspydeehunk2-May-11 20:54 
GeneralRe: A method that accepts a List can only accept a List (or some... PinmemberPatolia Sanjay2-May-11 21:30 
Generalwhat is the use of IEnumerable here because if i want to hav... Pinmemberspydeehunk2-May-11 18:13 
GeneralRe: String is just an example here, we can collect reference typ... PinmemberPatolia Sanjay2-May-11 18:16 
GeneralPerformance Pinmemberkornman0028-Apr-11 7:36 
GeneralRe: Performance PinmemberPatolia Sanjay2-May-11 18:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 29 Apr 2011
Article Copyright 2011 by Sanjay J Patolia
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid