Options for initializing a string array

169,341

Solution 1

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"; // ...

Solution 2

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();

Solution 3

string[] str = new string[]{"1","2"};
string[] str = new string[4];
Share:
169,341

Related videos on Youtube

mrblah
Author by

mrblah

test testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest test asdf asdf

Updated on July 08, 2022

Comments

  • mrblah
    mrblah almost 2 years

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

  • LukeH
    LukeH over 14 years
    Don't forget the string[] items = { "Item1", "Item2", "Item3", "Item4" }; shortcut.
  • skinnedKnuckles
    skinnedKnuckles about 9 years
    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[,])?