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

What are the Different Array Initialization Syntaxes in C#?

Barbara Streisand
Release: 2025-01-31 22:21:10
Original
869 people have browsed it

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>
    Copy after login
    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>
    Copy after login
  • Create a new array with initialized expressions:

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

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

    <code class="language-csharp">int[] numbers = [1, 2, 3, 4, 5];</code>
    Copy after login
    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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template