0

Good day, I cant figure out why i cant make the following Array:

 Label[] labels = new Label[25] { label1, label2, label3, label4, ... label 25 };

Just underneath this statement i`ve got the Working Array:

int[] array2 = new int[] { 1, 3, 5, 7, 9 };

The error that VS gives me on the labels 1 to 25 are: a field initializer cannot reference the non-static, method, or property 'Class.Forms1.label1'

The next link shows us that the intarray is correct, but why is my LabelArray incorrect? http://msdn.microsoft.com/en-us/library/9b9dty7d.aspx

Note: both arrays are tested inside and outside an function.

3
  • I want to use it outside an method, in a method with static and the size of the array, doesn` t work either Commented Feb 4, 2014 at 19:33
  • @Steve As per the error message; this is a field initializer, not code in a static method. Commented Feb 4, 2014 at 19:35
  • @Steve The message is rather self explanatory in my eyes. A field initializer cannot reference other members of the instance. That's what he's doing, and that's not allowed. Calling an instance member for a static method is an entirely different error message. Commented Feb 4, 2014 at 19:40

1 Answer 1

1

As the error indicates, you cannot refer to other instances fields of the same instance in the initializer for another instance field.

Your int array isn't refering to any other fields, it's simply adding compile time literal values as the values of the array.

You simply need to create your array in the type's constructor, rather than as a field initializer:

public class Foo
{
    private Label label1, label2;
    private Label[] labels;
    public Foo()
    {
        labels = new []{ label1, label2 };
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.