arrays_initializers.md - brainchildservices/curriculum GitHub Wiki

Slide 1

C# Array Initializers

To make C# initialize arrays, developers apply the new keyword. Consider this code:

 int[] array1 = new int[6];

C# creates an array and reserves memory space for six integers. However, the initialization process does not end here.

It is important to assign values to the array. The most useful way to create arrays and produce quality code is declaring, allocating, and initializing it with a single line:

 int[] array1 = new int[6] { 3, 4, 6, 7, 2};

Every element in an array has a default value which depends on the array type. When declaring an int type, you make C# initialize array elements to 0 value.

Slide 2

Multi-Dimensional Arrays

C# multi-dimensional arrays have multiple rows for storing values. It is possible to make C# declare arrays that have either two or three dimensions.

With the following code, C# creates a two-dimensional array (with [,]):

 int[,] array = new int[5, 3];

You can create three-dimensional arrays using this code:

 int[, ,] array1 = new int[4, 2, 3];

Slide 3

Jagged Arrays

C# arrays are jagged when they hold other arrays. The arrays placed in jagged arrays can have different sizes and dimensions.

With the following code, we generate a single-dimensional array with four other single-dimensional int type arrays:

 int[][] jaggedArray = new int[4][];

It is crucial to make C# declare arrays and initialize them with the following code:

 jaggedArray[0] = new int[4];
 jaggedArray[1] = new int[5];
 jaggedArray[2] = new int[3];

We created three single-dimensional arrays: the first one contains 4 integers, the second contains 5 integers, and the last one has 3 integers.

 jaggedArray[0] = new int[] { 7, 2, 5, 3, 8 };
 jaggedArray[1] = new int[] { 4, 5, 7, 8 };
 jaggedArray[2] = new int[] { 14, 18 };

Note: Remember: the elements of jagged C# arrays are reference types, and their default value is null.

C# Array: Useful Tips

  • The number and length of dimensions of C# arrays cannot be modified after they are declared.
  • Arrays are great for code optimization because developers can store multiple values in one variable instead of creating multiple variables.
  • The square brackets ([]) after the element type indicate that it is an array.

Ref: https://www.bitdegree.org/learn/c-sharp-array#initialization-of-arrays