0

I have the following string, which I split and store into a List of strings. Afterwards when I'm going to use these elements, I am getting an error of "Indexoutofrange" but how is this possible ?

the string:

"getName():String
getTitle():String
getStaffNo():Int
getRoom():String
getPhone()"

my code:

List<myObject> myObjectList = new List<myObject>();

// in valueList Im now storing the string input and also split them at the whitespaces
List<string> valueList = System.Text.RegularExpressions.Regex.Split(stringValue, @"\s{2,}").ToList<string>();

foreach (string stringValue in valueList)
{
   // in tmp variable I'm splitting the stored string at ':' because the left side of the split is the name of the object und the right side is the type
   var tmp = stringValue.Split(':');
   myObject object1 = new myObject()
   {
      object1.name = tmp[0];
      object1.type = tmp[1];
   };

   myObjectList.Add(object1);
}

After I just run my unit Test Im getting all object.name right, so "getName", "getTitle", "getStaffNo", "getRoom" and "getPhone" are correctly stored in each object but the type refers to an error => "IndexOutOfRangeException". I just can't explain the exception because there should be at tmp[1] the value "String" stored

Can someone help me out please?

brstkr
  • 1,423
  • 3
  • 18
  • 28
  • 3
    Can you modify your code to be valid C# that will compile? If I fix the syntax errors, I get no `IndexOutOfRangeException` which likely means your source string is not what you think it is. – NetMage Dec 26 '19 at 20:54
  • 2
    *there should be at tmp[1] the value "String" stored* ... obviously not. What does the debugger tell you about the value in `stringValue` and that `tmp` array? That should give you (and us) some clue. See also: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – rene Dec 26 '19 at 20:56
  • 1
    Ok, I just found my problem, it was in the string because there was also one item without a type like "getPhone()" there was no ':' or "String" and at this point, the program just got crashed. – brstkr Dec 26 '19 at 21:29

0 Answers0