Learn All About C# Array in This In-depth Tutorial. It Explains How To Declare, Initialize And Access Arrays Along with Types And Examples Of Arrays in C#:
Our previous tutorial in this C# series explained all about C# Functions in detail.
In one of our earlier tutorials, we learned how variables in C# can be used to contain information about a certain data type. However, there is a problem with the variable i.e. it can store only one literal value.
For Example, int a = 2, imagine a situation where we want to store more than one value, it will become too cumbersome to define a variable for each and every value that we want to store. C# offers an array to solve this problem.
=> Read Through The C# Guide For Beginners Here
Table of Contents:
Arrays In C#
An Array can be defined as a special data type that can store a number of values arranged sequentially using its designated syntax. Arrays can also be defined as a collection of variables of the same data types stored in a sequential memory location.
Unlike the data type variable, we do not declare an individual variable for each value, instead, we declare an array variable from which the specific elements can be accessed by using an array index.
For Example, if we define an array variable as “Name”. We can access its content at different memory locations by using index like Name[0], Name[1], Name[2]… etc.
The above image is a graphical representation of a one-dimensional array. It has five elements (represented by each cube) that can be accessed by using specific indexes.
Pros And Cons Of Arrays
Enlisted below are some of the advantages of Arrays:
- Random access to values stored at different memory locations.
- Easy data manipulation like Data sorting, Data traversing or other operations.
- Optimization of code.
The only disadvantage that an array possess is its size restriction. Arrays are of definite size.
Types Of Arrays In C#
The C# programming language offers 3 different types of Arrays:
- 1 dimensional or Single Dimensional Array
- Multi-Dimensional Array
- Jagged Array
Single Dimensional Arrays
One dimensional array allows us to store data in a sequential manner. Let’s say we need to store the name of all the students in a class. The array provides a simpler way to store similar data types, hence we can store all the student names in an array.
How To Declare An Array in C#?
An array can be declared by using a data type name followed by a square bracket followed by the name of the array.
int[ ] integerArray; string[ ] stringArray; bool[ ] booleanArray;
Likewise, you can declare an array for different data types.
How To Initialize An Array in C#?
(i) Defining Array With The Given Size
An array can be initialized and declared together by using the new keyword. To initialize an array for 3 students. We need to create an array with size 3.
string[ ] student = new string[ 3 ];
The first part “string” defines the data type of the array, then we provide the array name. Then after writing equals to we initialize and provide the size of the array. i.e. 3.
(ii) Defining Array And Adding Values To Them
This is quite similar to the previous example, just with a difference of curly braces containing values of the array.
string[ ] student = new string[ 3 ]{“student1”, “student2”, “student3”};
(iii) Declaring The Array With Elements
In this type of declaration, we directly declare the array without providing the array size. The number of values we provide will automatically decide the size. For Example, if we are providing 3 values, then the array will be of size 3.
string[ ] student = {“student1”, “student2”, “student3”};
Accessing Value From An Array
To access any element from an array we need to access the array using index name. This can be done by placing an index of the element inside a square bracket preceded by the array name.
For Example, if we have initialized and declared the following array:
string[ ] student = {“student1”, “student2”, “student3”};
Then we can retrieve the value by using index”.
student[0] ;
This will return “student1”.
But why zero? It is because the counting of an array starts from zero instead of one. Hence, the first value will be stored at index zero, next at one and so on. This should also be kept in mind while assigning values to an array as it will throw an exception in case of overfilling.
Using For Loop To Access Arrays
Let’s write a program to access values from an array using for loop.
string [] std = new string[3] {“student1”, “student2”, “student3”}; /* value of each array element*/ for (int i = 0; i < 3; i++ ) { Console.WriteLine("std[{0}] = {1}", i, std[i]); } Console.ReadKey();
The output of the above program will be:
std[0] = “student1”
std[1] = “student2”
std[2] = “student3”
As we know, we can access the element by providing an index in the square bracket. That’s the same approach we took in the above program. We looped through each index and printed the value to the console.
Let’s try to use the same example with a simple for each loop.
Using For-Each Loop To Access Arrays
string [] std = new string[3] {“student1”, “student2”, “student3”}; /* looping through value of each array element*/ foreach (string s in std ) { Console.WriteLine(s); } Console.ReadKey();
The output of the above program will be:
student1
student2
student3
Properties And Methods Used With Arrays
Array class is the base class for all the arrays defined in the C#. It is defined inside the system namespace and provides various methods and properties for performing operations on arrays.
Let’s discuss some of the most commonly used methods in C#
Clear
It clears the element present in the array. Depending upon the data type the array elements can be converted to zero, false or null.
Syntax
Array.Clear(ArrayName, Index of starting element, number of element to clear);
string [] std = new string[3] {“student1”, “student2”, “student3”}; /* looping through value of each array element*/ foreach (string s in std ) { Console.WriteLine(s); } /* clearing the array by providing parameters */ Array.Clear(std, 0, 3); foreach (string s in std ) { Console.WriteLine(s); } Console.ReadKey();
The output of the above program will be:
student1
student2
student3
Array. Clear statement accepts three parameters, first is the name of the array, the second one is the starting index of the range of elements to clear and the third one is the number of elements to be cleared.
In our example, we started from the index “0” and cleared all three elements. You can provide your own parameters as per the requirement.
GetLength
It returns the length of the array i.e. the number of the element present inside the array.
Syntax
ArrayName.Length;
string [] std = new string[3] {“student1”, “student2”, “student3”}; /* looping through value of each array element*/ foreach(string s in std){ Console.WriteLine(s); } int len = std.Length; Console.WriteLine(“The length of array is: ”+len); Console.ReadKey();
The output of the above program will be:
student1
student2
student3
The length of array is: 3
In the above program, as length returns an integer value, we have stored the value in an integer variable and printed the same to the console.
IndexOf
It retrieves the index of the first occurrence of a specified object from a one-dimensional array.
Syntax
Array.IndexOf(NameOfArray, Element_Value);;
string [] std = new string[3] {“student1”, “student2”, “student3”}; /* looping through value of each array element*/ foreach (string s in std ) { Console.WriteLine(s); } int len = Array.IndexOf(std, "student3"); Console.WriteLine(len); Console.ReadKey();
The output of the above program will be:
student1
student2
student3
2
The IndexOf accepts two parameters, first is the array name and the next parameter is the value of the element inside the array.
Reverse(Array)
It reverses the sequences of the element present in an array.
Syntax
Array.Reverse(NameOfArray);
string [] std = new string[3] {“student1”, “student2”, “student3”}; /* looping through value of each array element*/ foreach (string s in std ) { Console.WriteLine(s); } Array.Reverse(std); /* looping through value of each array element*/ foreach (string s in std ) { Console.WriteLine(s); } Console.ReadKey();
The output of the above program will be:
student1
student2
student3
student3
student2
student1
The Reverse accepts one parameter i.e.the array name.
In the above example first, we have printed the elements from the array. Then we performed a reverse operation on the array. Next, we have printed the result of the reverse operation.
Sort(Array)
It sorts the sequences of the element present in an array.
Syntax
Array.Sort(NameOfArray);
string [] std = new string[3] {"colt", "zebra", "apple"}; /* looping through value of each array element*/ foreach (string s in std ) { Console.WriteLine(s); } Array.Sort(std); foreach (string s in std ) { Console.WriteLine(s); } Console.ReadKey();
The output of the above program will be:
colt
zebra
apple
apple
colt
zebra
In the above output, you can see that the previous elements in the array were arranged as per the sequence we provided.
When we performed sort operation, all the elements inside the array gets arranged alphabetically.
Conclusion
In this tutorial, we learned about Arrays in C#. Arrays can store values of a similar data type in a series. The series index for arrays starts from zero. The array size needs to be specified during the initialization of the array.
We can access the value of an array by using indexing. C# Array helper class contains several different properties and methods to facilitate the operations on arrays.
=> Read Through The C# Guide For Beginners Here