1. Create your array based on the amount of data you need to add.
example:
int[] stuff = new int[100];
for (int i = 0; i < 100; i++)
{
//remember we can only index up to 99, not 100 as indexing starts at 0, not 1
stuff = i * 2; //will add 2,4,6,8,10...
}
return stuff;
if you don't know the size for sure and you can handle a small performance hit you can use either an ArrayList if using the 1.1 Framework or a List<> if you're using the 2.0 Framework.
1.1 Framework Example:
using System.Collections;
ArrayList stuff = new ArrayList();
for (int i = 0; i < 52; i++)
{
stuff.Add(i * 2); //add an integer to the arraylist. You can in fact add any object to an arraylist but be careful to stick to only the same type
}
return (int[])stuff.ToArray(typeof(int));
//In the above line, we are casting each object in the arraylist to an integer. If you mix datatypes you will throw an exception.
2.0 Framework Example:
using System.Collections.Generics;
List<int> stuff = new List<int>();
for (int i = 0; i < 38; i++)
{
stuff.Add(i * 3);
}
return stuff.ToArray(); //works because we KNOW it's an array of integers as specified in the <>
I hope that gives you a good understanding of arrays.
JurkMonkey - I have never had to work with an array in C# that I did not know what the size would be ahead of time, so I did not know that. Thank you for the good explanation of ArrayLists, surely worth another star
Ignorance of certain subjects is a great part of wisdom
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.