C# Arrays :

What Is an "Array"?

Arrays are vital for most programming languages. They are collections of variables, which we call elements. Arrays can be in different dimensions, but the most used are the one-dimensional and the two-dimensional arrays. One-dimensional arrays are also called vectors and two-dimensional are also known as matrices.

C# Arrays Declaration and Initialization :

In C# the arrays have fixed length, which is set at the time of their instantiation and determines the total number of elements. Once the length of an array is set we cannot change it anymore.

Declaration :

We declare an array in C# in the following way:

int[] myArray;

In this example the variable myArray is the name of the array, which is of integer type ( int[] ). This means that we declared an array of integer numbers. With [] we indicate, that the variable, which we are declaring, is an array of elements, not a single element.

When we declare an array type variable, it is a reference, which does not have a value ( it points to null ). This is because the memory for the elements is not allocated yet.


Array Initialization and Default Values :

Before we can use an element of a given array, it has to be initialized or to have a default value. In some programming languages there are no default values and then if we try to access an element, which is not initialized, this may cause an error. In C# all variables, including the elements of arrays have a default initial value. This value is either 0 for the numeral types or its equivalent for the non-primitive types (for example null for a reference type and false for the bool type). Of course we can set initial values explicitly. We can do this in different ways. Here is one of them:

int[] myArray = { 1, 2, 3, 4, 5, 6 };

Here is one more example how to declare and initialize an array:

string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday", "Sunday" };

Next Update

Loading...

We adding new programming language tutorials very soon.

We make a Collaboration with HackIsOn YouTube Channel So, Please Subscribe Their Channel and keep supporting