Curriculum
In C#, the Array
class is a built-in class that provides methods for working with arrays. The Array
class is part of the System
namespace, so you need to include this namespace at the beginning of your code file in order to use the Array
class.
Here are some of the most commonly used methods of the Array
class in C#:
Array.Copy()
: This method copies a range of elements from one array to another. Here is an example:int[] sourceArray = { 1, 2, 3, 4, 5 }; int[] destinationArray = new int[5]; Array.Copy(sourceArray, destinationArray, 5); Console.WriteLine(string.Join(", ", destinationArray)); // output: 1, 2, 3, 4, 5
2. Array.IndexOf()
: This method searches for the specified element in an array and returns the index of the first occurrence. Here is an example:
string[] stringArray = { "apple", "banana", "cherry", "apple" }; int index = Array.IndexOf(stringArray, "cherry"); Console.WriteLine(index); // output: 2
3. Array.Reverse()
: This method reverses the order of the elements in an array. Here is an example:
int[] intArray = { 1, 2, 3, 4, 5 }; Array.Reverse(intArray); Console.WriteLine(string.Join(", ", intArray)); // output: 5, 4, 3, 2, 1
4. Array.Sort()
: This method sorts the elements in an array. Here is an example:
int[] intArray = { 5, 3, 1, 4, 2 }; Array.Sort(intArray); Console.WriteLine(string.Join(", ", intArray)); // output: 1, 2, 3, 4, 5
5. Array.GetLength()
: This method returns the length of a specified dimension in an array. Here is an example:
int[,] multiArray = new int[3, 4]; int rows = multiArray.GetLength(0); int columns = multiArray.GetLength(1); Console.WriteLine(rows); // output: 3 Console.WriteLine(columns); // output: 4
6. Array.Clear()
: This method sets a range of elements in an array to a specified value. Here is an example:
int[] intArray = { 1, 2, 3, 4, 5 }; Array.Clear(intArray, 2, 3); Console.WriteLine(string.Join(", ", intArray)); // output: 1, 2, 0, 0, 0
7. Array.Resize()
: This method changes the size of an array. Here is an example:
int[] intArray = { 1, 2, 3 }; Array.Resize(ref intArray, 5); Console.WriteLine(string.Join(", ", intArray)); // output: 1, 2, 3, 0, 0
8. Array.BinarySearch()
: This method searches for a specified element in a sorted array using a binary search algorithm. Here is an example:
int[] intArray = { 1, 2, 3, 4, 5