Why has to be size of dynamically-allocated array a static field?

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;
    }
}

Answers


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:

class Foo
{
    private int x;
    private int y = x; // Invalid
}

From section 10.5.5.2 of the C# 3 spec:

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name.

I suspect you really want something like this:

class Foo
{
    private int x;
    private int y;

    private int[,] bar;

    public Foo( int a, int b )
    {
        x = a;
        y = b;
        bar = new int[x, y];
    }
}

Of course you don't really need x and y at all - they're just convenient to keep each dimension of the array. You could also use bar.GetLength(0) and bar.GetLength(1) to get the two lengths, but that's not terribly pleasant.

You might want to rename x and y to width and height though, or something similar :)


The example shown of 'Foo will never have the array 'bar be anything but an an array of size [0,0] : it's instantiation occurs before you call the class constructor.

Try this :

public class Foo2
{
    private int[,] bar;

    public Foo2(int a, int b)
    {
        bar = new int[a,b];
    }
}

That will give you an array of size [a,b] without use of 'static.


Need Your Help

A button next to an EditText

android android-listview xamarin android-edittext android-button

In Xamarin, I have a Layout with an EditText that I can enter text into to search for a Location.

rhc command for openshift Mysql ip

php mysql openshift openshift-client-tools

i need Mysql IP for custom wordpress installation as it not support "localhost" mysql host address.In rhc window client i use port forward command rhc port-forward -a appname but it show openshift IP