C # forms an objectArray method outside of a method

Good afternoon, I cannot understand why I cannot make the following array:

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

Under this statement, I have a working array:

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

The error that VS gives me on labels 1 through 25: the field initializer cannot refer to the non-static method or property "Class.Forms1.label1"

The following link shows us that 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 the function.

0
object arrays c # visual-studio
source share
1 answer

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

Your int array does not refer to any other fields, it just adds compilation time limit values ​​as array values.

You just need to create your array in the type constructor, and not as a field initializer:

 public class Foo { private Label label1, label2; private Label[] labels; public Foo() { labels = new []{ label1, label2 }; } } 
+1
source share

All Articles