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,元素为默认值的数组
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,并已填充元素的数组
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,并已填充元素的数组
This syntax combines the statement and initialization into a line, simplifying the code.
string[] array = new[] { "A", "B" }; // 创建一个长度为2,并已填充元素的数组
C# 12 allows simple array initialization when the target type cannot be inferred from the right.
string[] array = ["A", "B"]; // 创建一个长度为2,并已填充元素的数组 (C# 12及更高版本)
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!