Index was outside the bounds of the array の原因と直し方
配列やリストの範囲外アクセスで実行時に発生します。ループの境界条件の誤りが典型的な原因です。
エラーメッセージの読み方
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
System- 名前空間 — System なら標準の基本例外です
IndexOutOfRangeException- 例外クラス — 何が起きたか。ここを検索するのが最短です
Index was outside the bounds of the array.- 詳細メッセージ — どの値が問題だったか
at Program.Main(String[] args) in Program.cs:line 4- 発生箇所 — スタックトレースの先頭行
このエラーが出る典型パターン
パターン1
1 class Program { 2 static void Main(string[] args) { 3 int[] nums = { 1, 2, 3 }; 4 System.Console.WriteLine(nums[5]); ^ 5 } 6 }
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.Main(String[] args) in Program.cs:line 4
配列の添字は0から始まり、末尾はLength-1です。3個の配列に5番目の要素はありません。
直し方: 5 を 1 にします。
広告
広告スロット(未設定)
パターン2
1 class Program { 2 static void Main(string[] args) { 3 int[] nums = { 10, 20, 30 }; 4 for (int i = 0; i <= nums.Length; i++) { ^ 5 System.Console.WriteLine(nums[i]); 6 } 7 } 8 }
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.Main(String[] args) in Program.cs:line 5
ループの継続条件が<=だと、末尾を1つ超えたインデックスまでアクセスしてしまいます。
直し方: <= を < にします。
パターン3
1 class Program { 2 static void Main(string[] args) { 3 int[] nums = { 1, 2, 3 }; 4 int idx = -1; ^ 5 System.Console.WriteLine(nums[idx]); 6 } 7 }
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.Main(String[] args) in Program.cs:line 5
C#の配列は負のインデックスを末尾からの参照として扱いません(Pythonとは違います)。
直し方: -1 を 0 にします。
よくある誤解
配列の範囲外アクセスはコンパイルエラーにならず、実行時に初めて発覚します。ループの継続条件の<=は特に見落としやすい原因です。
まとめ
Index was outside the bounds of the arrayは初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。
関連するエラー
- Object reference not set エラー(null参照)の原因C#で最も有名な実行時エラーです。
- Attempted to divide by zero の原因と直し方整数の除算・剰余演算で除数が0のときに発生します。