Home >Backend Development >C++ >How Many Ways Can I Initialize an Array in C#?

How Many Ways Can I Initialize an Array in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-31 22:26:10956browse

How Many Ways Can I Initialize an Array in C#?

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:

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn