I have a class with a List and I am accessing it in another classes method. That works fine but when I attempt to use the List in a do-loop I always get a “ArgumentOutOfRangeExcetpion”. I’m really confused why using the List inside a do-loop caused it to be empty or at least that’s what I think is happening. If some one could explain to me why this is happening it would be very enlightening and maybe I could figure out how I’m gonna get this to work.
Here is my Method:
private void ListToAttributes()
{
int count = -1;
//Finds Attribute starting Line.
do
{
count = count + 1;
} while (Player.PlayerList[count] != "Attributes;");
//Adds all Attributes to a list
List<string> TypeAndAmount = new List<string>();
do
{
TypeAndAmount.Add(Player.PlayerList[count]);
count = count + 1;
} while (Player.PlayerList[count] != ".");
//Sorts by type and adds amount to Player Class
foreach (string Line in TypeAndAmount)
{
string[] Type = Line.Split(' ');
if (Type[0] == "Mind") { Player.Mind = int.Parse(Type[1]); }
if (Type[0] == "Body") { Player.Body = int.Parse(Type[1]); }
if (Type[0] == "Soul") { Player.Soul = int.Parse(Type[1]); }
}
}
You first loop will cause an
ArgumentOutOfRangeExceptionif no item in the list matches the string. In this case you will happily walk past the end of the list. Your second loop has the same issue.Further I think you have to increment
countone more time between the two loops – currently you are adding the item"Attributes;"to the listTypeAndAmount. This will also cause anArgumentOutOfRangeExceptionbecause splitting the string"Attributes;"at spaces yields only one string and you are accessingType[1]in your last loop.I suggest rewriting your code using some LINQ (including the step to skip the item
"Attributes;").You can also put everything into one statement – less verbose but harder to debug.