How to initialize array dynamically?

  • Thread starter Thread starter Brett
  • Start date Start date
B

Brett

I need an array but don't know how many items will go into it upon
declaration.

int ArrayIndex = 0;
string[] linkArray = new string[]{};

for (int i = 0; i < Links.Count; i++)
{
linkArray[ArrayIndex] = u.AbsoluteUri;
ArrayIndex++;
}

The first time through the loop, I get an out of bounds error. How exactly
does the array need to work in this case?

Thanks,
Brett
 
Brett said:
I need an array but don't know how many items will go into it upon
declaration.

Hi. Use an ArrayList instead.

System.Collections.ArrayList linkArrayList = new
System.Collections.ArrayList();
for (int i = 0; i < Links.Count; i++) linkArrayList.Add(u.AbsoluteUri);
string[] linkArray = (string[]) linkArrayList.ToArray(typeof(string));

-- Alan
 
Brett said:
I need an array but don't know how many items will go into it upon
declaration.

int ArrayIndex = 0;
string[] linkArray = new string[]{};

for (int i = 0; i < Links.Count; i++)
{
linkArray[ArrayIndex] = u.AbsoluteUri;
ArrayIndex++;
}

The first time through the loop, I get an out of bounds error. How exactly
does the array need to work in this case?

In this case, it's easy - you *do* know the number of links:

string[] linkArray = new string[Links.Count];

(You don't need the ArrayIndex variable either; just use i.)

If you genuinely don't know ahead of time how many items you need, use
an ArrayList and if you need to, call ToArray on the ArrayList.
 
Alan Pretre said:
Brett said:
I need an array but don't know how many items will go into it upon
declaration.

Hi. Use an ArrayList instead.

System.Collections.ArrayList linkArrayList = new
System.Collections.ArrayList();
for (int i = 0; i < Links.Count; i++) linkArrayList.Add(u.AbsoluteUri);
string[] linkArray = (string[]) linkArrayList.ToArray(typeof(string));

-- Alan
This worked great. Thanks.

Brett
 
Jon Skeet said:
Brett said:
I need an array but don't know how many items will go into it upon
declaration.

int ArrayIndex = 0;
string[] linkArray = new string[]{};

for (int i = 0; i < Links.Count; i++)
{
linkArray[ArrayIndex] = u.AbsoluteUri;
ArrayIndex++;
}

The first time through the loop, I get an out of bounds error. How
exactly
does the array need to work in this case?

In this case, it's easy - you *do* know the number of links:

string[] linkArray = new string[Links.Count];

(You don't need the ArrayIndex variable either; just use i.)

If you genuinely don't know ahead of time how many items you need, use
an ArrayList and if you need to, call ToArray on the ArrayList.

Yeah - I had to use the arrylist because links.count isn't the number I
need. I'm actually looping through that and looking for links that match a
specific pattern.

Brett
 
Back
Top