4

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.

2
  • 1
    missing new keyword Commented Sep 26, 2013 at 20:02
  • 1
    Arrays are objects - you need to new one up.... Commented Sep 26, 2013 at 20:02

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

But this works and is also an array in the constructor: int[] values2 = { 1, 2, 3 };. Why does it work for local variables?
0

Try following

int[] values = new int[]{a, b, c};

Comments

0

This would work:

values = new[] { a, b, c };

Or

values = new int[] { a, b, c };

Further Reading

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.