ArgumentOutOfRangeException on initialized List

随声附和 提交于 2019-11-26 23:18:05

You cannot index into a list if that offset doesn't exist. So, for example, indexing an empty list will always throw an exception. Use a method like Add to append the item to the end of the list, or Insert to place the item in the middle of the list somewhere, etc.

For example:

var list = new List<string>();
list[0] = "foo"; // Runtime error -- the index 0 doesn't exist.

On the other hand:

var list = new List<string>();
list.Add("foo");       // Ok.  The list is now { "foo" }.
list.Insert(0, "bar"); // Ok.  The list is now { "bar", "foo" }.
list[1] = "baz";       // Ok.  The list is now { "bar", "baz" }.
list[2] = "hello";     // Runtime error -- the index 2 doesn't exist.

Note that in your code, this is happening when you write to the Courses list, and not when you read from the Course_ID list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!