C# Array Methods

Let's see some useful array and instance methods.

Overview

In C#, our arrays derive from the .NET System.Array class, so all of the System.Array methods for working with arrays and array elements are available to our arrays.

System.Array provides static methods, such as IndexOf(), and instance methods, such as SetValue().

Instance Methods

Instance methods are called using the array instance such as booktitles in our example below. To access an instance method, type the array instance variable and a dot (.).

For example, we will change a value of an element in the booktitles array below:

//intialization, declaration and populating an array
var booktitles = new[] {"Brain Rules", "Pragmatic Programmer",
                "Harry Potter and the Half-Blood Prince",
                "The Alchemist" };
            
booktitles.SetValue("Harry Potter", 2);

//iterating through an array using foreach
foreach (var title in booktitles)
{
    Console.WriteLine($"The book title is {title}");
}

Output: implicit

Static Methods

To access a static method type Array then dot (.).

Let’s try the IndexOf() static method of Array, it returns the index number of a specific element.

//intialization, declaration and populating an array
var booktitles = new[] {"Brain Rules", "Pragmatic Programmer",
                "Harry Potter and the Half-Blood Prince",
                "The Alchemist" };
            
var alchemistIndex = Array.IndexOf(booktitles, "The Alchemist");
Console.WriteLine($"The Alchemist is in index {alchemistIndex}");

Output: implicit


πŸ”š end of document πŸ”š

References