1

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

2 Answers 2

5

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 :)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Please note that J. Skeet's prescient comment on Henk's answer would also apply to my first statement above concerning the original class 'Foo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.