What are the options for initializing a string array in C#

Rahul Kiwitech
Rahul K...
292 Points
26 Posts

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

Views: 8729
Total Answered: 2
Total Marked As Answer: 0
Posted On: 26-Apr-2017 02:22

Share:   fb twitter linkedin
Answers
Jak
Jak
908 Points
132 Posts
         

We have several way to initialize array of string

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

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

string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...
Posted On: 27-Apr-2017 02:40
edx
edx
506 Points
24 Posts
         

These are the correct declaration and initialization ways for a simple array of string in C#.

string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2

Note that you can obtain arrays from Linq ToArray() extensions on IEnumerable<T>.

Also note that in the declarations above, you can replace the first two string[] on the left with var (C# 3.0+). But for third one as the information on the right is enough to infer the proper type, must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. So the above could be written as

var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
Posted On: 27-Apr-2017 02:58
 Log In to Chat