C# Arrays

tutorial and example
tutorial and example

Like in other programming languages, in C# the array can be defined as a collection of similar type of objects which have contiguous memory allocation. Array index starts from zero(0). It is an object of the base class System.Array .

Advantages of using arrays:

  1. Code reusability
  2. Random access
  3. Less code
  4. Easy traversing
  5. Easy manipulation

Disadvantages:

  1. Can’t increase its size at runtime.

Collections are used in C# to overcome size related problems of array.

Types of array:

  1. Single dimensional array
  2. Multi dimensional array
  3. Jagged array

Single Dimensional Array

Single dimensional array is the array which has a single dimension and doesn’t require any row or columns on a high level. It is stored in contiguous memory location.

Declaring 1D Array :

To declare 1D array, we have to use square brackets [] after the data type. Let’s see the syntax:

Syntax

Example:

let’s see a simple example which initialize and traverse 1D array

Output

Declaring and initializing 1D array at the same time:

We can declare and initialize 1D array at the same time. Let’s see how can we do it .

int[] arr=new int[5]{10,20,30,40,50};

We are not required to use size

int[] arr=new int[]{10,20,30,40,50};

We can omit new operator also

Int[] arr={10,20,30,40,50};

Let’s see a simple example of initializing 1D array.

Output

Traversing array using foreach loop

We can use foreach loop in C# to traverse array elements. Let’s see how can we do it.

Output