Array in C#
When we want to store more than one value of single datatype in a variable, we use arrays.So we can say that arrays are strongly types.
How to Create an Array Variable :
I believe if we go by example it would be the best approach for easy understanding. Suppose I want to store even numbers. In that case, I would create an array variable named “EvenNumbers” which would be of datatype int as even numbers are integers.
int[] EvenNumbers = new int[5];
The “[ ]”square brackets followed by the integer datatype means that the variable name “EvenNumbers ” is supposed to be an array. We use the new keyword followed by the datatype int[3] to tell the compiler that when the array variable is created it can store only 3 values of integer datatype.
How to Assign Value to Array Variable :
The array variable have indices starting from 0 , so if they can have only 3 values in them, you can start adding value to the array member that has an indices (index) value of 0 till 2.
For Ex : In our case
EvenNumbers[0]=2;
EvenNumbers[1]=4;
EvenNumbers[2]=6;
How to Access a particular Array Value ?
In our case, lets say we want to print the second value of the array i.e. n-1 where n is the position number of the value you want to access. So, EvenNumbers[n-1] will be EvenNumber[1] = 4; To print this value lets create this program to understand better ;
Ex :
using System; class array_ex { public static void main() { Int[] EvenNumbers = new int[3]; EvenNumbers[0]=2; EvenNumbers[1]=4; EvenNumbers[2]=6; Console.WriteLine(EvenNumbers[1]); } }
Advantages of using Array :
They are strongly typed i.e. if an array is declared to be integer array it can not accept string value.
Disadvantages of Array :
If you already assign an array the number of values (in our case 3) , you can not add more values into it after it reaches its limit.