Home >Backend Development >C#.Net Tutorial >Detailed explanation of how to initialize C# array

Detailed explanation of how to initialize C# array

高洛峰
高洛峰Original
2016-12-16 14:46:541845browse

How to initialize the array? Here we will introduce you to the specific steps and example demonstrations of C# array initialization in detail. I hope it will be helpful for you to understand and learn how to initialize an array, so let’s get started:

C# encloses the initial value in curly brackets ({}) It provides a simple and straightforward way to initialize an array at declaration time. In particular, if the array is not initialized when declared, the array members are automatically initialized to the default initial value of the array type.

The following examples show various methods of initializing arrays of different types.

C# array initialization one-dimensional array

int[] numbers = new int[5] {1, 2, 3, 4, 5}; string[] names = new string[3] {"Matt", "Joanne ", "Robert"};

You can omit the size of the array, as follows:

int[] numbers = new int[] {1, 2, 3, 4, 5}; string[] names = new string [] {"Matt", "Joanne", "Robert"};

If an initializer is provided, the new statement can also be omitted, as follows:

int[] numbers = {1, 2, 3, 4, 5}; string[] names = {"Matt", "Joanne", "Robert"};

C# array initialization multi-dimensional array

int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary"," Albert"} };

The size of the array can be omitted, as follows:

int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} } ; string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Ray"} };

If an initializer is provided, new can also be omitted Statement, as shown below:

int[,] numbers = { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = { {"Mike", "Amy"} , {"Mary", "Albert"} };

C# array initialization of interleaved arrays (arrays of arrays)

You can initialize interleaved arrays as shown in the following example:

int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

The size of the first array can be omitted, as follows Shown:

int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

Or use

int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

Note that for interleaved arrays The elements have no initialization syntax.

The relevant content of C# array initialization is introduced to you here. I hope it will be helpful for you to understand and learn C# array initialization.



For more detailed explanations on how to initialize C# arrays, please pay attention to 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