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.
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.
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