views:

212

answers:

3

I want to store few strings into an array using ArrayList.

How can I store all the strings at once without using Add function every time. Is it somewhat related to interface ICollection in anyway. Can I use ICollection to store my array. If yes How.

ArrayList _1019=new ArrayList("TEN","ELEVEN","TWELVE","THIRTEEN","FOURTEEN","FIFTEEN","SIXTEEN","SEVENTEEN","EIGHTEEN","NINETEEN");

I want to store this in the constructor of a class in C#

+4  A: 

C# 3.0

ArrayList arrayList = new ArrayList() { "foo", "bar" }; // or
ArrayList arrayList = new ArrayList{ "foo", "bar" };
PieterG
+8  A: 

Well, you can create an array, and populate the ArrayList from that:

ArrayList _1019 = new ArrayList(new string[] { "TEN", "ELEVEN", "TWELVE",
    "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN",
    "NINETEEN" });

That will work with all versions of C#, and all versions of .NET.

As PieterG says, C# 3 has collection initializers - but I suspect that if you're still using ArrayList, you may not be using C# 3.

If you are using C# 3 and targeting anything other than the micro framework, I suggest you use List<string> instead of ArrayList.

Jon Skeet
+1 Jon, I was thinking the same thing about using ArrayList in C# 3. thanks for clearing that up for Shantanu Gupta
PieterG
A: 

You don't even need an ArrayList try

string[] stringArray = "red,yellow".Split(",")

this will return a string array

then you can stringArray.ToList() for a generic list of strings

which would be the modern equivilent to an ArrayList

danswain