Array.IndexOf() / Array.Copy()
The Array.IndexOf() method searches an array for a specified value, and the Array.Copy() method copies elements from one array to another.
Syntax
// Returns the index of the first occurrence of value in the array. Returns -1 if not found. Array.IndexOf(T[] array, T value) // Copies length elements from sourceArray starting at sourceIndex to destinationArray starting at destinationIndex. Array.Copy(T[] sourceArray, int sourceIndex, T[] destinationArray, int destinationIndex, int length) // Copies length elements from the beginning of sourceArray to the beginning of destinationArray. Array.Copy(T[] sourceArray, T[] destinationArray, int length)
Method List
| Method | Description |
|---|---|
| Array.IndexOf(T[] array, T value) | Returns the index of the first element in the array that matches value. Returns -1 if not found. |
| Array.IndexOf(T[] array, T value, int startIndex) | Starts the search at startIndex and returns the index of the first matching element. |
| Array.Copy(Array src, Array dst, int length) | Copies length elements from the beginning of src to the beginning of dst. |
| Array.Copy(Array src, int srcIdx, Array dst, int dstIdx, int length) | Copies length elements from src starting at srcIdx to dst starting at dstIdx. |
Sample Code
using System;
// Use Array.IndexOf() to find the position of an element.
string[] languages = { "C#", "Java", "Python", "Go", "Rust" };
int index = Array.IndexOf(languages, "Python");
Console.WriteLine(index); // 2
// Returns -1 if the value is not found.
int notFound = Array.IndexOf(languages, "Swift");
Console.WriteLine(notFound); // -1
// Example of using it as an existence check.
string search = "Java";
if (Array.IndexOf(languages, search) != -1)
{
Console.WriteLine($"{search} exists in the array.");
}
// Use Array.Copy() to copy an entire array.
int[] source = { 10, 20, 30, 40, 50 };
int[] dest = new int[source.Length];
Array.Copy(source, dest, source.Length);
dest[0] = 999;
Console.WriteLine(source[0]); // 10 (the original array is unchanged)
Console.WriteLine(dest[0]); // 999
// Partial copy example (copy 3 elements starting at index 1 into dest starting at index 0).
int[] partial = new int[3];
Array.Copy(source, 1, partial, 0, 3);
Console.WriteLine(string.Join(", ", partial)); // 20, 30, 40
Notes
Array.Copy() performs a shallow copy. If the array contains reference-type elements (such as class instances), the copied elements will reference the same objects as the original array. This is not an issue for value-type arrays (such as int or double).
To inspect the contents of an array, first check the element count using Length / Array.Resize(), then access elements within the valid index range.
If you find any errors or copyright issues, please contact us.