Mark
Mark

Reputation: 4883

Out of Range Exception - Substring - C#

I have a list of phone numbers some with extensions, some with out. I regex my phone number to return just the digits.

I then create a string for the first 10 digits(area code + number).

I compare this strings length and compare it to the original. If there is a difference, I use the remainder as the extension.

In the code below, I keep getting an out of range exception. I've debugged it, and it does not appear to be out of range. Anyone see what I'm missing?

var prePhone = emp.y.PhoneNumber;

if (!string.IsNullOrEmpty(prePhone))
{
    string xPhone = Regex.Replace(prePhone, "[^0-9]", "");
    string number = xPhone.Substring(0, 10);
    int extMath = xPhone.Length - number.Length;

    if (extMath >= 1)
    {   int preExt = 9 + extMath;
        string ext = xPhone.Substring(10, preExt);//Out of range exception
        em.Phone = beautifyPhoneNumber(number, ext);
    }
    else {
        string ext = null;
        em.Phone = beautifyPhoneNumber(number, ext);
    }
}

Upvotes: 0

Views: 574

Answers (1)

Dan Byström
Dan Byström

Reputation: 9244

string ext = xPhone.Substring(10, preExt)

The second argument is not the ending index, it is the length of the string you want to extract.

Since preExt > 10 in your code, xPhone must be more than 20 characters in length, (since you're starting at index 10), otherwise an exception will be thrown.

Upvotes: 4

Related Questions