When I run the code bellow in the console application I got the error " Index was outside the bounds of the array". Why do I get the error and how to fix it?
static void Main(string[]args)
{
string aString= "This is a string";
string [] sArray= aString.Split(' ');
Console.WriteLine(sArray[sArray.Length]);
}
I thinks,should I convert the sArray.Length to int because it still be a string form. right?
Loading
Ankit NandekarPosted Apr 19, 2011, 12:45 AM
static void Main(string[] args)
{
string aString = "This is a string";
string[] sArray = aString.Split(' ');
Console.WriteLine(sArray[sArray.Length-1]);
}
you r getting error bcoz u r trying to access array value which is out of index range bcoz array starting from 0 and ur last array index will be 3 and u r trying to access index 4 because sArray.Length is 4 here.Thats why u r getting this error.
Chandra Sekhar KPosted Apr 19, 2011, 12:28 AM
sArray.Length will be 4.
Since the array positions starts from 0(Length calculation starts from 1) , the array will be having the four positions as of 0,1,2,3.
4 is outside the four positions, it throws the error.