Home >Backend Development >C++ >How Many Ways Can I Initialize an Array in C#?
C#array initialized multiple methods
The most direct method is to use
New keywords, followed by array type and required size:
<code class="language-csharp">string[] array = new string[2]; // 创建长度为 2 的数组,初始化为默认值</code>or, you can use the specific value of the bracket syntax to initialize the array during the creation period:
<code class="language-csharp">string[] array = new string[] { "A", "B" }; // 创建长度为 2 的数组,初始化为 "A" 和 "B"</code>You can also list the value only in parentheses, without using
New Keywords:
<code class="language-csharp">string[] array = { "A", "B" }; // 创建长度为 2 的数组,初始化为 "A" 和 "B"</code>In addition, you can use
VAR to infer the type of array from the initial grammar:
<code class="language-csharp">var array = new[] { "A", "B" }; // 创建长度为 2 的已填充数组,类型从值推断</code>Finally, C# 12 introduces a collection expression, allowing simple array initialization without the need to specify the type:
<code class="language-csharp">string[] array = ["A", "B"]; // 创建长度为 2 的已填充数组,类型从值推断</code>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!