In the following code, why is it necessary for the array (arr) to be static ?
If I remove static, then it is no more visible for using in the LINQ query.
class A
{
static int[] arr = { 1, 2, 3, 4 };
IEnumerable<int> result = from i in arr where i < 10 select i;
}
Thanks.
You cannot access other class instance variables if you directly initialize variables using a variable initializer - you could move the code to the constructor instead:
class A
{
int[] arr = { 1, 2, 3, 4 };
IEnumerable<int> result;
public A()
{
result = from i in arr where i < 10 select i;
}
}
From the C# spec, 10.5.5.2 Instance field initialization:
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.
This makes sense, since variable initializers are executed before the base class constructor, hence the class instance has not been fully "constructed" yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With