I have a dummy class where I am testing arrays. I’ve noticed that when I want to dynamically allocate size of array at runtime, fields that indicate this size have to be static. I know I should probably use collections for this kind of code, but I’m more interested why do these fields have to be static? Is there any particular reason behind this?
class Foo
{
private static int x;
private static int y;
private int[,] bar = new int[ x, y ];
public Foo( int a, int b )
{
x = a;
y = b;
}
}
They don’t really have to be static – it’s just that you can’t refer to other instance variables within instance variable initializers. In other words, it’s a bit like this:
From section 10.5.5.2 of the C# 3 spec:
I suspect you really want something like this:
Of course you don’t really need
xandyat all – they’re just convenient to keep each dimension of the array. You could also usebar.GetLength(0)andbar.GetLength(1)to get the two lengths, but that’s not terribly pleasant.You might want to rename
xandytowidthandheightthough, or something similar 🙂