Reputation: 261
The following code gives errors:
public class SomeClass
{
private int a;
private int b;
private int c;
private int[] values;
public SomeClass()
{
a = 1;
b = 2;
c = 3;
values = {a, b, c};
}
public static void Main()
{
SomeClass sc = new SomeClass();
}
}
I want values to contain a,b, and c.
I also tried initializing the array outside of the constructor like this.
private int[] values = {a, b, c};
and initializing it fully inside the constructor like this:
int[] values = {a, b, c};
but none of these do the trick.
Upvotes: 4
Views: 1867
Reputation: 564931
Arrays are an object and require you to explicitly use new
to construct them.
You can use:
values = new int[] {a, b, c};
Or the even shorter syntax:
values = new[] {a, b, c};
On a side note, if you're writing the array declaration and initialization in one statement, you can actually write them as you did:
int[] values2 = { a, b, c};
However, since you have values
declared as a field, this won't work within the constructor for the values initialization, as you're initializing separate from your declaration.
Upvotes: 7
Reputation: 149108
This would work:
values = new[] { a, b, c };
Or
values = new int[] { a, b, c };
Further Reading
Upvotes: 0