Top 5 array methods in C# with examples

An array in C# is a collection of variables that are stored together in a contiguous block of memory. Arrays are used to store multiple values in a single object, and can be used to store values of any data type, including primitive types like integers and strings, and reference types like objects.

Arrays are defined using the [] operator, followed by the type of data that the array will hold. For example, here is how you might declare and initialize an array of integers in C#:

int[] numbers = { 1, 2, 3, 4, 5 };

You can also specify the size of the array when you create it, like this:

int[] numbers = new int[5];

This creates an array with 5 elements, all of which are initialized to their default value (0 for integers).

But, which are the top 5 used methods in arrays in C#?

Array.Sort

This method sorts the elements in an array in ascending order. Example:

int[] numbers = { 3, 1, 4, 2 };
Array.Sort(numbers);
// numbers is now [1, 2, 3, 4]
Array.Reverse

This method reverses the order of the elements in an array. Example:

int[] numbers = { 1, 2, 3, 4 };
Array.Reverse(numbers);
// numbers is now [4, 3, 2, 1]
Array.IndexOf

This method searches an array for a specific value, and returns the index of the first occurrence of that value. If the value is not found, it returns -1. Example:

int[] numbers = { 1, 2, 3, 4 };
int index = Array.IndexOf(numbers, 3);
// index is now 2
Array.Clear

This method sets all the elements of an array to a default value (usually 0 or null). Example:

int[] numbers = { 1, 2, 3, 4 };
Array.Clear(numbers, 0, numbers.Length);
// numbers is now [0, 0, 0, 0]
Array.Resize

This method changes the size of an array, either by adding or removing elements. Example:

int[] numbers = { 1, 2, 3, 4 };
Array.Resize(ref numbers, 6);
// numbers is now [1, 2, 3, 4, 0, 0]

Image by Freepik


Enjoyed this post? Subscribe to my YouTube channel for more great content. Your support is much appreciated. Thank you!


Check out my Udemy profile for more great content and exclusive learning resources! Thank you for your support.
Ervis Trupja - Udemy



Enjoyed this blog post? Share it with your friends and help spread the word! Don't keep all this knowledge to yourself.