Hello i have a problem with c# Arrays. I need a array to store some data in there... My Code is that
double[] ATmittelMin;
ATmittelMin[zaehlMittel] = Gradient(x, xATmax, y, yATmax);
But the compiler says: not defined var How can i define a double array without a fixed size ? Thanks a lot!
The obvious solution that springs to mind is to use a List:
But if you don't want to convert from a list to an array you can grow the array later:
It's not ideal as you're doing a lot of the work that
List
is doing behind the scenes - probably a lot more efficiently than you can.Arrays are always fixed in size, and have to be defined like so:
The
List<T>
class uses an array in the background and redefines it when it runs out of space:You can iterate through a
List<T>
just as you would an array:From what I see you did not declare the
zaehlMittel
variable. I guess this is what the compiler complains about.Apart from that, even though you can of course determine the value of that variable programmatically, the moment you want to create an array its size must be known. This is the way arrays work.
In case you cannot do that easily, I suggest using some sort of dynamic datastructure, like a list or a set. Then, once all elements have been added, you are of course still free to create an array from that, as by that time you know the number of elements (even though there are convenience methods like
toArray()
that will even take care of that).You have to instanciate the array before using it: