How do I initialize an array? Here is a detailed introduction to the specific steps and examples of C # array initialization, which hopefully helps you understand and learn how to initialize arrays, so let's get started:
C # provides a simple and straightforward way to initialize an array at declaration time by enclosing the initial value in curly braces ({}). It is particularly important to note that if an array is not initialized at the time of declaration, the array member is automatically initialized to the default initial value of the array type.
The following example shows various methods for initializing arrays of different types.
C # Array initialization one dimension 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 you provide an initializer, you can also omit the new statement, as follows:
int[] numbers = {1, 2, 3, 4, 5}; String[] names = {"Matt", "Joanne", "Robert"};
A multidimensional array of C # array initialization
int[,] numbers = new int[3, 2] {{1, 2}, {3, 4}, {5, 6}}; string[,] siblings = new string[2, 2] {"Mike", "Amy"}, {"Mary", "Albert"};
You can omit the size of the array, as follows:
int[,] numbers = new int[,] {{1, 2}, {3, 4}, {5, 6}}; string[,] siblings = new string[,] {{"Mike", "Amy"}, {"Mary", "Ray"}};
If you provide an initializer, you can also omit the new statement, as follows:
int[,] numbers = {{1, 2}, {3, 4}, {5, 6}}; string[,] siblings = {"Mike", "Amy"}, {"Mary", "Albert"};
C # Array initialization interleaved array (array of arrays)
You can initialize a jagged array 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:
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 there is no initialization syntax for elements of a jagged array.
The contents of C # array initialization are introduced here, and hopefully it will help you understand and learn about C # array initialization.