What is C# Array?
The array is a data structure in C# that can store multiple variables of the same type.
For example, you want to store the product_id of the products or roll numbers of the students that are integer types.
One way can be declaring and storing the values in the primitive type variables. The other way can be creating an array that can store n number of int type variables for storing the product_id or roll_no etc.
The next sections describe how to create, initialize, and use arrays. I will also show you examples of various array types; single dimensional, multi-dimensional and Jagged arrays.
How to create and initialize an Array in C#?
The general syntax of creating/declaring an array is:
For example:
int[] intArray;
string[] strArray;
The array can be initiated at the time of declaration. For example:
int[] intArray = new int[] { 5, 10, 14, 21 };
string[] strArray = new string[] {“abc”,”def”,”ghi”,”klm”};
An example of declaring, initiating, and accessing array elements
Let us start with a simple example of declaring and initializing an int-type array of five elements.
This is followed by using a C# for loop with the array length property to access and display the array elements:
using System; class array_demo { static void Main() { //Declaring and initializing an array int[] intArr = new int[] { 15, 35, 50, 75, 100 }; for (int l = 0; l < intArr.Length; l++) { Console.WriteLine(intArr[l]); } Console.ReadLine(); } }
The result:
15
35
50
75
100
The example of C# string array
The example below creates an array of string type and then its items are accessed by using for loop and displayed on the screen:
The code:
using System; class array_demo { static void Main() { //Declaring and initializing a string array string[] strArrName = new string[] { "Hine", "Tina", "Mina", "Nazo", "Marie" }; Console.WriteLine("****The Names in Array:****\n"); for (int x = 0; x < strArrName.Length; x++) { Console.WriteLine("\t" + strArrName[x]); } Console.ReadLine(); } }
The output:
Using foreach loop to iterate through array elements example
You may also use foreach loop to iterate through the array elements.
using System; class array_demo_foreach { static void Main() { //Declaring a byte array byte[] bteArrNums = new byte[] { 1, 3, 5, 7 }; foreach (byte num in bteArrNums) { Console.WriteLine("the Byte Array Item = " + num); } Console.ReadLine(); } }
The example of using Array sort method
Before showing you how to create multi-dimensional and jagged arrays in C#, let us have a look at a few useful methods and a property of the Array class.
For that, we have an array of byte type with random numbers.
Then a foreach loop is used to display the array elements which is followed by using the sort() method.
To see the difference, the array elements are displayed again after sorting the array:
using System; class array_demo_sort { static void Main() { //Declaring a byte array byte[] bteArrSort = new byte[] { 99, 8, 5, 11, 21, 4 }; Console.WriteLine("***Array Before Sorting***\n"); foreach (byte num in bteArrSort) { Console.WriteLine("\t" + num); } Array.Sort(bteArrSort); Console.WriteLine("\n***Array After Sorting***\n"); foreach (byte num in bteArrSort) { Console.WriteLine("\t" + num); } Console.ReadLine(); } }
Sorting only a range of items
You may also specify the range of elements to be sorted by providing indices. For example, if we have the same array as above example:
We are required to sort it from second to fourth elements only then the sort() method can be used as follows:
The result of this should be (if you iterate through this array and display the items):
99
5
8
11
21
4
The example of Array IndexOf method
So, if the specified array has duplicate occurrences, the method returns only the first found element’s position.
using System; class array_demo_IndexOf { static void Main() { int[] intArr_indexOf = new int[] { 15, 35, 50, 75, 100, 15, 75 }; //Using the Array IndexOf method int x = Array.IndexOf(intArr_indexOf, 75); Console.WriteLine("The Position of the element = " + x); Console.ReadLine(); } }
The result:
You may notice, we searched 75 in the array. It occurred twice in the array while IndexOf returned the index position of the first 75 i.e. 3.
You may search a part of the array rather than a complete array by specifying the range of elements.
For example, if we used the IndexOf method like this in the above example:
The result should be:
As such, we specified to start searching the array from position 4.
An example of Array length property
You might have noticed, we used it in our first example in the for loop.
It set the condition part in the for loop as shown below:
for (int l = 0; l < intArr.Length; l++)
{
Console.WriteLine(intArr[l]);
}
The example below shows the total number of elements in a string array by using the length property of the Array:
using System; class array_demo_length { static void Main() { string[] strArrAlphabets = new string[] { "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz" }; Console.WriteLine("Total Number of Elements in String Array = " + strArrAlphabets.Length); Console.ReadLine(); } }
The output of the above code:
An example of C# multi-dimensional array
C# supports multi-dimensional arrays. The general syntax of creating a 2D array of string type is:
Where Arr2D is the array name.
Similarly, a three dimensional array can be declared as follows:
The example below shows how to create a two-dimensional array in C#.
using System; class array_demo_2D { static void Main() { string[,] Arr2D = new string[3, 2] { { "Mango", "Apple" }, { "Banana", "Strawberry" }, { "Pine Apple", "Peach" } }; int x, y; for (x = 0; x < 3; x++) { for (y = 0; y < 2; y++) { Console.WriteLine("x[{0},{1}] = {2}", x, y, Arr2D[x, y]); } } Console.ReadLine(); } }
The result:
C# Jagged array example
See an example below for declaring, initializing, and accessing a jagged array of string type:
using System; class array_demo_Jagged { static void Main() { string[][] ArrJagged = new string[][] {new string[]{"abc","def"}, new string[]{"ghi","kjl"}, new string[]{"mno","pqr"}, }; int i, j; Console.WriteLine(ArrJagged[0][0]); Console.WriteLine(ArrJagged[0][1]); Console.WriteLine(ArrJagged[1][0]); Console.WriteLine(ArrJagged[1][1]); Console.ReadLine(); } }
The result:
abc
def
ghi
kjl
Summary of C# Arrays Tutorial
This C# arrays tutorial covers fundamental aspects of array manipulation and usage. Here are the key points:
- Array declaration and initialization: Learn the syntax for declaring and initializing arrays of different data types, including both fixed-size and dynamic initialization.
- Accessing array elements: Explore various methods to access and iterate through array elements, including using for loops and foreach loops.
- Useful methods and properties: Discover essential methods like sort() for sorting elements, IndexOf for searching elements, and length property for retrieving the total number of elements.
- Multi-dimensional arrays: Go beyond one-dimensional arrays and learn how to create and use two-dimensional and three-dimensional arrays.
- Jagged arrays: Understand the concept of jagged arrays and how to declare, initialize, and access their elements.