How to initialize a string array in C#?
In C#, there are several ways to initialize a string array:
- Initialize a string array with specified elements using curly braces {}.
string[] arr1 = {"apple", "banana", "orange"};
- Initialize an empty string array with a specified size using the new keyword, and then assign values using indexes.
string[] arr2 = new string[3];
arr2[0] = "apple";
arr2[1] = "banana";
arr2[2] = "orange";
- Initialize a string array with default values by using the new keyword and initializing the elements’ values.
string[] arr3 = new string[3] {"apple", "banana", "orange"};
- Initialize a string array using the static methods of the Array class.
string[] arr4 = Array.Empty<string>(); // 初始化一个空的字符串数组
string[] arr5 = Array.CreateInstance(typeof(string), 3) as string[]; // 初始化指定大小的字符串数组
The above are several common ways to initialize string arrays. Choose the appropriate method based on your specific needs.