why argument out of range exception ?

  • Thread starter Thread starter smith flyers
  • Start date Start date
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
 
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.
 
On your first iteration the value of word is ""

This will generate the error when you call Substring


Brian W
 
Back
Top