Monday, May 18, 2020

C# Tutorial: 07 - Arrays in C#

Tutorial: 07 - Arrays in C#

    An array is container of fixed size which stores the elements with same data type. You can think an array as collection same data type's variables with contagious memory location. Arrays in C# are indexed based and starts with 0 index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Array Declaration

data_type[] array_name;
data type: for specifying the data type of array
[] : for specifying the size of array
array_name : for array name as per rules of variable declarations
When an array is declared, memory is not assigned to it. It is done with initialization. In C#, An Array is reference type, so use of new keyword is used for creating an array. For example in following example we are declaring an integer array of size 6:
int[] marks = new int[6];

Array Initialization

You can assign values to an array in following manner:

int[] marks = new int[6];
marks[0] = 32;
marks[1] = 44;
You can also assign values at time of declaration like this:
int[] marks = {23, 45, 34};
You can also assign values like this:
int[] marks = new int[3] {32, 42, 21};
Accessing Array Elements
For accessing a single array item you can do something like this:
Console.WriteLine(marks[0]); 
Or you can use a loop in order to access elements of array like this:

The output of above program will be like this:
Element at 0 index = 32
Element at 1 index = 43
Element at 2 index = 64
Element at 3 index = 42
Element at 4 index = 54
Element at 5 index = 62

In later lessons, we will also discuss Multidimensional and jagged arrays.
Also we will see how to pass arrays as parameters to methods.

No comments:

Post a Comment