Link to home
Start Free TrialLog in
Avatar of tonelm54
tonelm54

asked on

ArgumentOutOfRangeException

Ive been looking at a way to split a long string into segments, and come up with the following function:-
        static string[] Split(string str, int chunkSize)
        {
            int arraySize = new int();

            if (str.Length % chunkSize == 0) {
                arraySize = str.Length / chunkSize;
            } else {
                arraySize = (str.Length / chunkSize)+1;
            }

            string[] n = new string[arraySize]; 

            for (int x = 1; x<=arraySize; x++) {
                n[x] = str.Substring((x * chunkSize), (x * (chunkSize - 1)));
            }
            return n;
        }

Open in new window


Seems to run through fine, for first serveral runs, however then fails saying:-
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

I dont understand why its failing cause it doesnt seem to be out of range :-S

Im new to c# and could do with any assistance in pointing out my error.

Thank you
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

You are probably use to program in VB. In C#, when you declare an array, you do not specify the upper index, you are specifying the size of the array. Thus, string[10] is indexed from 0 to 9, not from 0 to 10 as it would be in VB.

If arraySize is 10, the following is then trying to access [10], that does not exist: x<=arraySize

Try with x<arraySize
ASKER CERTIFIED SOLUTION
Avatar of MikeToole
MikeToole
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial