-1

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.

1
  • From Mohamed Hazeem: Can you explain about obj? if obj is class then mod be a like: var modifications = new List<string>() {"1", "10", "100", "101", "102", "0"}; var obj = new Obj(); foreach (var item in modifications ) { obj.Mod1.Add(item.ToString()); } Commented Jul 7, 2023 at 10:44

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

1 Comment

thanks but found this myself now but anyway thank for the help
0

Are the values really named Mod1 through Mod6? If these were columns in a database table, we would say that the table is not normalized. In this case are more scalable and flexible way would be to have Mod be an array of strings string[]. Then you could simply write:

obj.Mod = modifications.ToArray();

And you could access the Mods using loops.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.