why argument out of range exception ?

S

smith flyers

string thingword=" testing hmmm";

string firstLetter,restOfWord;

foreach (string word in thingword.Split())

{

Console.WriteLine(word); // if this only use for output and the rest in
the block is commented, no error !!!

firstLetter = word.Substring(0,1);

restOfWord = word.Substring(1, word.Length -1);

Console.WriteLine(firstLetter);

Console.WriteLine(restOfWord);

}





error:::



Unhandled Exception: System.ArgumentOutOfRangeException: Index and length
must r
efer to a location within the string.
Parameter name: length
at System.String.Substring(Int32 startIndex, Int32 length)
at Class1.jimmy.Main(String[] what) in c:\documents and settings\jim\my
docum
ents\visual studio projects\consoleapplication1\class1.cs:line 43
Press any key to continue
 
G

Gareth

what if the word = a single character, i.e. word = "A"

That would cause the word.Substring(1, word.Length - 1); to fail with that
error.
 
B

Brian W

On your first iteration the value of word is ""

This will generate the error when you call Substring


Brian W
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top