Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

return an array? 2

Status
Not open for further replies.

Sidro

MIS
Sep 28, 2002
197
0
0
US
Hi folks.
I have a function that creates an array, add numbers to them and finally, I would like it to return the array to the caller.

Whats the correct syntax for this?
thanks.
 
public int[] GetArray()
{
int[] stuff = new int[]{1,3,5,7,9};

return stuff;
}
 
Wow, thanks for the quick response.
Just what I was looking for.
Another question though.

for this line" int[] stuff = new int[]{1,3,5,7,9};"

suppose I dont add values to the array when instantiating.
If I add the values later, is it true I have to do this for each index?

ex.

int [] stuff=new int[3];

stuff[0]=new int();
stuff[1]=new int();
stuff[2]=new int();

thanks.

 
No, that would almost make it worthless to use an array :)

You should just be able to set, for example

stuff[0] = 3;

Hope this helps,

Alex


Ignorance of certain subjects is a great part of wisdom
 
There are 2 options...

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
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top