Reputation: 179
I am new to C# and am testing on return types using array and a class. But Somehow I am stuck while trying to return a class' object. In class notWhole, I tried to pass an array as an argument to the constructor but somehow compiler throws an error saying "field initializer can't initialize non static field member".
class Whole
{
int[] Arr = new int[3];
public Whole()
{
}
public Whole(int[] arr)
{
Arr = arr;
}
public int[] Spit()
{
return Arr;
}
}
class notWhole
{
int[] arr = new int[] { 1, 2, 3 };
Whole w1 = new Whole(arr); //ERROR: can't pass an array(arr) as an argument
public Whole wow()
{
return w1;
}
}
Upvotes: 2
Views: 75
Reputation: 1396
C# does not allow you to access in initializers section other fields or methods You could use a constructor for your purposes. Also, if you use a static then you could create some side effects since all of your Whole instances will have a reference to same static array and a change in one of you Whole instance will be "available" in all others.
class notWhole
{
Whole w1;
public notWhole()
{
int[] arr = new int[] { 1, 2, 3 };
w1 = new Whole(arr);
}
public Whole wow()
{
return w1;
}
}
Upvotes: 1
Reputation: 29036
I think that error message is enough to identify the reason, ie.,
A field initializer cannot reference the non-static field, method, or property
So you can try like this:
Whole w1 = new Whole(new int[] { 1, 2, 3 });
or like this :
static int[] arr = new int[] { 1, 2, 3 };
Whole w1 = new Whole(arr);
Upvotes: 2