C# Arrays

« Previous Tutorial Next Tutorial »

Array is used to store a fixed-size sequential collection of elements of same data type. All the arrays consist of contiguous memory locations, where the lowest address corresponds to the first element of the array whereas the highest address corresponds to the last element of the array.

Declare an Array in C#

Here is the general form to declare an array in C#:

data-type[] array-name;

Here, data-type represents the element type in the array, [] specify the size of the array or elements size that this array can store, and then array-name is the name of the array. Here is an example of declaring an array named marks, that can store upto 10 elements (subject's marks) of int data type:

int[] marks;

Initialize an Array in C#

In C#, declaring an array doesn't initialize the array inside the memory. When the array variable is initialized, then you becomes free to assign the values to the array. Here is the general form to initialize an array in C#. You have to use the keyword named new to create an instance of the array like this:

data-type[] array-name = new data-type[array-size];

Here is an example of initializing an array in C#:

int[] marks = new int[10];

Assign Values to an Array in C#

Now, you can assign values to the individual array elements just by using their index number like this:

marks[0] = 94;

You are also free, to assign values to the array at the time of declaration like this:

int[] marks = {98, 87, 89, 90, 96, 93, 78, 67, 93, 84};

Here is another way to create and initialize an array in C#:

int[] marks = new int[10] {98, 87, 89, 90, 96, 93, 78, 67, 93, 84};

Access Array Elements in C#

Array elements are simply accessed by indexing the array name. Here is an example, accessing the the 4th element present in the array marks:

int sub1 = marks[3];

Note - Index always starts from 0. So 3rd index represents to the 4th element.

C# Arrays Example

Here is an example program, demonstrating the concept of arrays in C#:

/* C# Arrays - Example Program */
using System;
namespace ArrayExample
	class ArrayClass
		static void Main(string[] args)
			int[] marks = new int[10];
			int i;
			int j;
			int num=80;
			for(i=0; i<10; i++)
				marks[i] = num;
			for(j=0; j<10; j++)
				Console.WriteLine("Marks[{0}] = {1}", j, marks[j]);

When we compile and run the above program, it will produce the following output:

Marks[0] = 80
Marks[1] = 81
Marks[2] = 82
Marks[3] = 83
Marks[4] = 84
Marks[5] = 85
Marks[6] = 86
Marks[7] = 87
Marks[8] = 88
Marks[9] = 89

C# Online Test

« Previous Tutorial Next Tutorial »

© Copyright 2021. All Rights Reserved.