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

What are the Different C# Array Initialization Syntaxes?

Patricia Arquette
Release: 2025-01-31 22:41:13
Original
513 people have browsed it

What are the Different C# Array Initialization Syntaxes?

C# When the array in C#is created, it can initialize its elements through a variety of grammar, which provides flexibility and convenience in various programming scenarios. The following is possible grammar:

This syntax creates a specified array with a default element, which is suitable for the situation that needs to initialize each element later.

string[] array = new string[2]; // 创建一个长度为2,元素为默认值的数组
Copy after login

Elements are provided directly in the array initialization, and this syntax uses the specified value to fill the array.

string[] array = new string[] { "A", "B" }; // 创建一个长度为2,并已填充元素的数组
Copy after login

This syntax is similar to the previous grammar, but does not explicitly specify the new string array. The compiler infer the type based on the value provided.

string[] array = { "A" , "B" }; // 创建一个长度为2,并已填充元素的数组
Copy after login

This syntax combines the statement and initialization into a line, simplifying the code.

string[] array = new[] { "A", "B" }; // 创建一个长度为2,并已填充元素的数组
Copy after login
The collection expression introduced in

C# 12 allows simple array initialization when the target type cannot be inferred from the right.

string[] array = ["A", "B"]; // 创建一个长度为2,并已填充元素的数组 (C# 12及更高版本)
Copy after login
By using these different array initialization syntax, you can enhance your C#programming experience according to specific needs and preferences.

The above is the detailed content of What are the Different C# Array Initialization Syntaxes?. For more information, please follow other related articles on the PHP Chinese website!

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