中級 › ArgumentOutOfRangeException の原因と直し方 › パターン1
ArgumentOutOfRangeException の原因と直し方
List<T>のインデクサに範囲外の値を渡すと発生します。
1 class Program { 2 static void Main(string[] args) { 3 var nums = new System.Collections.Generic.List<int> { 1, 2, 3 }; 4 System.Console.WriteLine(nums[__]); ^ 5 } 6 }
Unhandled exception. System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
at Program.Main(String[] args) in Program.cs:line 4
空欄を埋めてビルドを通す
List<T>のインデクサは配列と違い、範囲外を指定するとArgumentOutOfRangeExceptionを投げます(配列のIndexOutOfRangeExceptionとは型が違います)。
次の問題