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 I开发者_运维问答Collection 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#
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
.
C# 3.0
ArrayList arrayList = new ArrayList() { "foo", "bar" }; // or
ArrayList arrayList = new ArrayList{ "foo", "bar" };
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
精彩评论