C# string toCharArray out of range exception

I came across this issue while I was fixing someone else's code. apparently they were trying to control digits after the decimal point like this:

public static bool check_count(double d)
    {
        string str = d.ToString();
        bool b = true;
        if (str.IndexOf('.'))
        {
            char[] ch = str.ToCharArray(str.IndexOf('.'), str.Length - 1);
            if (ch.Length > 5)
                b = false;
        }
        return b;
    }

I wasn't going to bother myself fixing that since I'm replacing it with regular expressions but it made me curious. the ToCharArray is throwing ArgumentOutOfRangeException when it shouldn't(?!)

let's say

string str = "20.222";
Console.WriteLine(str);
int index = str.IndexOf('.');
if (index > -1)
{
   Console.WriteLine(index);
   Console.WriteLine(str.Length-1);
   char[] ch = str.ToCharArray(index, str.Length - 1);
}

output:

20.222
2
5

live demo [here]

so the string is 6 chars long and the start index is 2, what argument is out of what range?

I feel lost in this .. any ideas?

thanks

Jon Skeet
people
quotationmark

what argument is out of what range?

Well, I'd expect the exception to tell you that - but I'd also expect it to be the second argument. (EDIT: Looking at the exception you actually get, even from .NET, it's actually blaming the first argument. Admittedly it's the combination of the first and second arguments which is invalid, but it's more sensible to blame the second one in this case, as the first one is valid on its own.)

Look at the documentation - the second argument is the length, not the end index. So I suspect you want something like:

char[] ch = str.ToCharArray(index, str.Length - index);

Or to get just the digits after the .:

char[] ch = str.ToCharArray(index + 1, str.Length - index - 1);

people

See more on this question at Stackoverflow