Reputation: 357
The following works:
int[] numbers = new int[2];
The following doesn't:
int Size = 2;
int[] numbers = new int[Size];
Error: "A field initializer cannot reference the non-static field, method, or property"
I know this must be me doing something stupid but can't work out what it is at all.
Upvotes: 1
Views: 127
Reputation: 148120
You can give size of array by constant but not variable as the size of array could not be given at class level if you declare the array out side the method at class level. C# does not guarantee the order in which fields within a class are initialized so you cannot use one non-static field to initialize another non-static field outside of a method, reference.
const int Size = 2;
int[] numbers = new int[Size];
void SomeFun()
{
}
If you declare it inside some method then you wont get error.
void SomeFun()
{
int Size = 2;
int[] numbers = new int[Size];
}
You can use list instead of array if your collection size in unknown at runtime.
List<int> lst = new List<int>();
Upvotes: 4
Reputation: 11301
Put these initializations into the constructor:
public class MyClass
{
const int Size;
int[] numbers;
public MyClass()
{
this.Size = 2;
this.numbers = new int[this.Size];
}
}
In this way you are providing a guarantee of order in which initializations should be executed.
Upvotes: 1
Reputation: 620
You cannot use an instance variable to initialize another instance variable. There is no guarantee that the 'Size' variable will be initialized before the 'number' array. The initial values for fields need to use constants - it's not as restrictive as that; they can also reference static fields, methods or properties.
Upvotes: 0