中級 › ArgumentOutOfRangeException の原因と直し方 › パターン3
ArgumentOutOfRangeException の原因と直し方
List<T>のインデクサに範囲外の値を渡すと発生します。
1 class Program { 2 static void Main(string[] args) { 3 var names = new System.Collections.Generic.List<string> { "a", "b" }; 4 System.Console.WriteLine(names[__]); ^ 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
空欄を埋めてビルドを通す
要素数2のリストで有効なインデックスは0と1だけです。Countと最大インデックスを混同しないようにします。
次の問題