i am working with a project and facing a glitch i have a list of string values and have one class object and want to insert data to that object based on the list of string values. I am facing index out of bounds exception
Here is what i have tried
var modifications = new List<string>() {"1", "10", "100", "101", "102", "0"};
foreach (var item in modifications )
{
obj.Mod1 = item[0].ToString();
obj.Mod2 = item[1].ToString();
obj.Mod3 = item[2].ToString();
obj.Mod4 = item[3].ToString();
obj.Mod5 = item[4].ToString();
obj.Mod6 = item[5].ToString();
}
i want to put first value in list to Mod1 then second to Mod2 so on and so forth. Can any body tell me what will be the good approach here.
Thanks in advance.
>Solution :
You don’t need a loop.
obj.Mod1 = modifications[0];
obj.Mod2 = modifications[1];
obj.Mod3 = modifications[2];
obj.Mod4 = modifications[3];
obj.Mod5 = modifications[4];
obj.Mod6 = modifications[5];
The reason for the exception is that you loop the strings, so item is a string, for example "1", and then you access characters at index 5 which is out of the bounds of the string("5".Length==1).