Home >Backend Development >C++ >What are the Different Array Initialization Syntaxes in C#?

What are the Different Array Initialization Syntaxes in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-31 22:21:10870browse

What are the Different Array Initialization Syntaxes in C#?

C#array initialization method Detailed explanation

C# offers a variety of array initialization syntax:

    Create a new array with the default value:
  • <code class="language-csharp">int[] numbers = new int[5]; </code>
    Use the initial value to create a new array:
  • The direct use of value initialization of the array:
    <code class="language-csharp">string[] names = new string[] { "John", "Mary", "Bob" };</code>
  • Create a new array with initialized expressions:

    <code class="language-csharp">int[] numbers = { 1, 2, 3, 4, 5 };</code>
  • Collection expression (new features of C# 12):

    <code class="language-csharp">int[] numbers = new[] { 1, 2, 3, 4, 5 };</code>
  • Supplementary description:

    <code class="language-csharp">int[] numbers = [1, 2, 3, 4, 5];</code>
    The first two grammar can use
  • keywords (c# 3 introduced) for type inference.

The third grammar needs to be explicitly declared in front of the bracket. The fourth grammar uses

expression, which also supports type inference.
  • Collection expression grammar (fifth) is very useful when it cannot infer the target type from the initialization device. It is also suitable for span and list. var

The above is the detailed content of What are the Different Array Initialization Syntaxes 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