0

There might be similar questions already, but I think I have a specific case here

I'm trying to understand how an existing application is working and debugging it right now

It is a console application where I'm providing 6 parameters:

  1. JobName
  2. Boolean flag
  3. File location
  4. FileType
  5. Date
  6. FileAppID

I provide the list of parameters through the Command line arguments value under "Debug" section of the project

So, it look something like that: "MyJobName" "0" "C:\\MyFile.txt" "MyFileType" "20200318" "MyAppID"

Application has the following logic:

SortedList<string, string> L = new SortedList<string,string>();                

for (int i = 2; i <= args.GetLength(0) - 1; i++)
{
     L.Add(args[i].Split(':')[0], args[i].Split(':')[1]);
}

List<SqlParameter> p = new List<SqlParameter>();
p.Add(new SqlParameter("@JobName", args[0]));
string xmlResult = D.RunProcedureXmlString("SPU_GetJobInfo", p);

So, when I hit the line inside of the loop on the first iteration, the following run time error happens:

args[i].Split(':')[1]   'args[i].Split(':')[1]' threw an exception of type 'System.IndexOutOfRangeException'    string {System.IndexOutOfRangeException}

What is wrong with the existing logic and what is the solution?

I'm not sure if the fix will break what I guess worked before. Will need to test it later.

gene
  • 2,098
  • 7
  • 40
  • 98

1 Answers1

1

If one of the items in the args array does not have a : character in it, then calling Split(':') will return an array with only one item. Therefore, calling args[i].Split(':')[1] will throw an IndexOutOfRangeException.

Also, you should only call Split once so you can re-use the resulting array, rather than wasting cycles and memory calling it multiple times.

One way to resolve this issue is to first check to see if the result of splitting the string has the required number of parts:

for (int i = 2; i < args.GetLength(0); i++)
{
    var result = args[i].Split(':');
   
    if (result.Length < 2)
    {
        // Do something here if there aren't enough items
    }
    else
    {
        L.Add(result[0], result[1]);
    }
}

Or use a default value if there aren't enough items:

for (int i = 2; i <= args.GetLength(0) - 1; i++)
{
    var result = args[i].Split(':');
    var firstPart = result[0];
    var secondPart = result.Length > 1 ? result[1] : string.Empty; // Default value

    L.Add(firstPart, secondPart);
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43