I have a method that seems to occasionally corrupt a value for no reason I can figure out. The method takes a variable length param list of arguments. The arguments are name/value pairs. I loop through the pairs and put the value in a tab separated StringBuilder based on the name. I calculate a lastValueIndex variable on entering the method and use that number as a conditional to stop looping. The method works fine for hundreds of calls but at about the same point in my program, the value of lastValueIndex seems to get corrupted and I get a ‘System.IndexOutOfRangeException’ error at
if ((int)values[valueNum] == columnNum)
When the exception happens, the debugger says there are 12 arguments in the values array being passed to the method. Executing values.Length in the watch window also give 12. Since the value of lastValueIndex is set to values.Lengh -1 when entering the method, it should have a value of 11 and I don’t re-assign lastValueIndex anywhere else. But the debugger says lastValueIndex = 17 which is definitely out of range.
Any ideas why this might be happening?
private static bool foundColumn = false;
private static int valueNum = 0;
private static int columnNum = 0;
private static int lastValueIndex = 0;
public static void write(params object[] values)
{
lastValueIndex = values.Length - 1;
sbWrite.Clear();
valueNum = 0;
lock (loggerLock)
{
while (valueNum < lastValueIndex)
{
columnNum = 0;
foundColumn = false;
while (!foundColumn)
{
if ((int)values[valueNum] == columnNum)
{
//TODO need to do a better job formatting values to minimize length
if (columnNum == (int)ColumnNums.comment)
{
sbWrite.Append(values[valueNum + 1].ToString());
}
else
{
sbWrite.Append(((double)values[valueNum + 1]).ToString("f6"));
}
foundColumn = true;
}
else
{
columnNum = columnNum + 1;
}
}
sbWrite.Append(token);
valueNum = valueNum + 2;
}
}
Debug.Print(sbWrite.ToString());
sbWrite.AppendLine();
Array.Clear(writeArray, 0, writeArray.Length);
Array.Copy(UTF8Encoding.UTF8.GetBytes(sbWrite.ToString()), writeArray, sbWrite.Length);
logFile.Write(writeArray, 0, Array.IndexOf(writeArray, 0));
BTConsole.SendLine(sbWrite);
}