113

What options do I have when initializing string[] object?

nawfal
  • 66,413
  • 54
  • 311
  • 354
mrblah
  • 93,893
  • 138
  • 301
  • 415

3 Answers3

200

You have several options:

string[] items = { "Item1", "Item2", "Item3", "Item4" };

string[] items = new string[]
{
  "Item1", "Item2", "Item3", "Item4"
};

string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...
Will Eddins
  • 13,240
  • 5
  • 48
  • 85
  • 7
    Don't forget the `string[] items = { "Item1", "Item2", "Item3", "Item4" };` shortcut. – LukeH Oct 01 '09 at 16:19
18

Basic:

string[] myString = new string[]{"string1", "string2"};

or

string[] myString = new string[4];
myString[0] = "string1"; // etc.

Advanced: From a List

list<string> = new list<string>(); 
//... read this in from somewhere
string[] myString = list.ToArray();

From StringCollection

StringCollection sc = new StringCollection();
/// read in from file or something
string[] myString = sc.ToArray();
Blue Toque
  • 1,757
  • 14
  • 23
  • Can someone add an example of "From a List" above but for the case of loading the contents of 2 lists into a 2 dimensional array (not jagged ie double[,])? – skinnedKnuckles May 28 '15 at 22:19
2
string[] str = new string[]{"1","2"};
string[] str = new string[4];
Mike Blandford
  • 3,852
  • 4
  • 27
  • 32