Array
Array : An array is a fixed-size collection of the same type of elements. We know that variable can store single value but it does not support to store multiple values. So, C# introduced an array to overcome the problem.
Array is a reference type and it uses a namespace System.Array. Array is a fixed-size and store values from index 0 (LowerBound) to maximum array size (UpperBound).
Array declaration:
int[] intArray; // Integer array
string[] strArray; // String array
bool[] boolArray // Bool array
Array initialization:
You can declare and initialize an array at the same time. Otherwise, you can first declare an array and then initialize it which is known as late initialization.
// Declare and initialize an array at the same time
int[] intArray = new int[4]; // Integer array
string[] strArray = new string[4]; // String array
// First declare an array and then initialize
int[] intArray;
intArray = new int[4]; // Integer array
string[] strArray;
strArray = new string[4]; // String array
Note: You must have to assign size of an array at the time of initialization. Otherwise, you will get compile time error6>
int[] intArray = new int[]; // Error: Array creation must have array size or array initializer
int[] intArray = new int[]; // Error: Array creation must have array size or array initializer
Assign values to an array:
You can assign values to an array at time of initialization or later
int[] intArray = new int[4]{ 1,2,3,4 };
int[] intArray1 = { 1,2,3, 4 }; // Array size will be automatically determined based on the number of values
int[] intArray2;
intArray2 = new int[4]{ 1,2,3,4};
int[] intArray3 = new int[4];
intArray3[0]=1;
intArray3[1]=2;
intArray3[2]=3;
intArray3[3]=4;
Accessing an array values:
You can access or retrieve values(elements) of an array using index as below:
int[] intArray = new int[4]{ 1,2,3,4 };
// Using specific index
intArray[0];
intArray[1];
intArray[2];
intArray[3];
// Using for loop
for(int i=0; i < intArray.Length; i++)
Console.WriteLine(intArray[i]);
// Using foreach loop
foreach(var item in intArray)
Console.WriteLine(item);
SEO Service
Awesome post! Keep up the great work! 🙂
buy anabolic online
Thanks for the good article, I hope you continue to work as well.Спаситель на продажу