C#array initialized multiple methods
Arrays are important data structures for storing sets of the same type value. C# offers a variety of array initialization syntax, providing developers with flexibility and convenience.
The most direct method is to use
New keywords, followed by array type and required size:
string[] array = new string[2]; // 创建长度为 2 的数组,初始化为默认值
Copy after login
or, you can use the specific value of the bracket syntax to initialize the array during the creation period:
string[] array = new string[] { "A", "B" }; // 创建长度为 2 的数组,初始化为 "A" 和 "B"
Copy after login
You can also list the value only in parentheses, without using
New Keywords:
string[] array = { "A", "B" }; // 创建长度为 2 的数组,初始化为 "A" 和 "B"
Copy after login
In addition, you can use
VAR to infer the type of array from the initial grammar:
var array = new[] { "A", "B" }; // 创建长度为 2 的已填充数组,类型从值推断
Copy after login
Finally, C# 12 introduces a collection expression, allowing simple array initialization without the need to specify the type:
string[] array = ["A", "B"]; // 创建长度为 2 的已填充数组,类型从值推断
Copy after login
It should be noted that the initialization array of parentheses grammar cannot be used to determine the type of array. In this case, the type must be displayed before the parentheses.
The above is the detailed content of How Many Ways Can I Initialize an Array in C#?. For more information, please follow other related articles on the PHP Chinese website!