MeWrite Docs

IndexOutOfRangeException

C#で配列やリストのインデックスが範囲外の場合に発生するエラー

概要

IndexOutOfRangeException は、配列やコレクションの要素にアクセスする際に、有効範囲外のインデックスを指定した場合に発生する例外です。

エラーメッセージ

System.IndexOutOfRangeException: Index was outside the bounds of the array.

原因

1. 配列サイズを超えたアクセス

1
2
int[] numbers = new int[3]; // インデックス 0, 1, 2 のみ
numbers[3] = 10; // IndexOutOfRangeException

2. 負のインデックス

1
2
int[] arr = { 1, 2, 3 };
Console.WriteLine(arr[-1]); // IndexOutOfRangeException

3. 空の配列へのアクセス

1
2
int[] empty = new int[0];
Console.WriteLine(empty[0]); // IndexOutOfRangeException

4. ループの境界エラー

1
2
3
4
5
int[] arr = { 1, 2, 3 };
for (int i = 0; i <= arr.Length; i++) // <= は間違い
{
    Console.WriteLine(arr[i]);
}

解決策

1. 境界チェックを追加

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
int[] arr = { 1, 2, 3 };
int index = 5;

if (index >= 0 && index < arr.Length)
{
    Console.WriteLine(arr[index]);
}
else
{
    Console.WriteLine("インデックスが範囲外です");
}

2. foreachループを使用

1
2
3
4
5
6
7
int[] arr = { 1, 2, 3 };

// インデックスを使わない安全なループ
foreach (var num in arr)
{
    Console.WriteLine(num);
}

3. LINQを使用

1
2
3
4
5
6
7
8
int[] arr = { 1, 2, 3 };

// ElementAtOrDefault: 範囲外ならデフォルト値
int value = arr.ElementAtOrDefault(5); // 0(int のデフォルト)

// FirstOrDefault, LastOrDefault
int first = arr.FirstOrDefault(); // 1
int last = arr.LastOrDefault();   // 3

4. Listを使用(柔軟性向上)

1
2
3
4
5
var list = new List<int> { 1, 2, 3 };

// Listも範囲外でArgumentOutOfRangeExceptionをスローする
// しかし追加・削除が柔軟
list.Add(4);

5. Spanを使用(パフォーマンス重視)

1
2
3
4
5
6
7
8
int[] arr = { 1, 2, 3 };
Span<int> span = arr.AsSpan();

// スライスで安全にアクセス
if (arr.Length > 2)
{
    var slice = span.Slice(0, 2);
}

関連エラー

関連エラー

C# の他のエラー

最終更新: 2025-12-17