Is there a way to have a static class have static data that does not clear itself at the end of the function call?
i.e. given:
static class Class1
{
static int[] _array;
static Class1()
{
_array = new[] {2};
}
public static void FillArray()
{
List<int> temp = new List<int>();
for(int i=0;i<100;i++)
temp.Add(i);
_array = temp.ToArray();
}
public static int[] GetArray()
{
return _array;
}
}
How can I get GetArray() to return something other than null?
EDIT: I want to call this code:
int[] array1 = Class1.GetArray();
for (int i = 0; i < array1.Length;i++ )
Console.WriteLine(array1[i]);
Class1.FillArray();
for (int i = 0; i < array1.Length; i++)
Console.WriteLine(array1[i]);
and not get two 2s. How can I make that happen?
In this code, you are getting the memory address of the first int[] {2} array and storing that as array1. Then when you call FillArray() you are creating the new List of arrays, and only setting its memory back to the _array in the class, not array1. That is not a reference to the memory in the class, but to the actual original array. So then, when you loop back through, you are still looking at the same memory block.
You should probably be doing this instead:
Update
if you change your Class1 to look like this, you will see that you are changing the data in the class.
Because it will print out the elements in the array after each call.