Click here to Skip to main content
15,907,392 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Everyone,


I have declared an empty string array in c# and I am trying to fill it with some values. But each time it says 'index is outside the bound of array'. Of course it means that the value I am trying to insert is getting outside the array. But I am not able to find the fault in my code. Need some help.
Here is my code:

string[] week = new string[0];
int loop=14;

for(int i=1;i<=loop;i++)
   {
     weekNo=i+10;
     week[i-1]=weekNo.ToString(); //this line has error
}


What I have tried:

I tried declaring the array in other ways
string[] week = new string[0];
string[] week = new string[]{};
string[] week = new string[0]{};
string[] week = new string[0] {};

But it says same error.
Posted
Updated 22-Oct-17 9:25am
v2

1 solution

When you declare an array, you specify exactly how many elements it can contain, and that number can never change. It can't go up, it can't go down. So when you say this:
C#
string[] week = new string[0];
You declare a variable called week which contains a reference to a array which can holed zero strings. That means that any index value will automatically be outside the bounds of the array.
If you know how many items you want to store, use that in the definition:
C#
int loop=14;
string[] week = new string[loop];
 
for(int i=1;i<=loop;i++)
   {
   int weekNo=i+10;
   week[i-1]=weekNo.ToString(); 
   }
If you don't, then don;t use an array, use a List<T>:
C#
List<string> week = new List<string>();
int loop=14;
for(int i=1;i<=loop;i++)
   {
   int weekNo=i+10;
   week.Add(weekNo.ToString());
   }
You can subsequently use indexing on the collection to access individual elements, if you need to.
 
Share this answer
 
Comments
planetz 23-Oct-17 2:09am    
Great!! List worked!! Thank you!!
OriginalGriff 23-Oct-17 2:52am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900