-2

Why can't I just re-declare an array with commas?

static void Main(string[] args)
{
    short[] arr = new short[6] { 1,1,1,1,1,1 };

    if(1)
    {
        arr = {1,0,0,1,1,0}; // this line doesn't work
    }
}
7
  • short[] arr = { 1,1,1,1,1,1 }; Commented Jun 15, 2017 at 17:46
  • 5
    if(1), what is this javascript? Commented Jun 15, 2017 at 17:52
  • 3
    @Kyle that's fine, but if(1) will not compile in C#, and its much different from if(someBoolVar) See for yourself Commented Jun 15, 2017 at 18:00
  • 3
    Possible duplicate of Why can't I use array initialisation syntax separate from array declaration? Commented Jun 15, 2017 at 19:21
  • 1
    wtf, I did not vote to close it as "primarily opinion based", I voted to close it as duplicate of the question suggested by Horton. Commented Jun 15, 2017 at 19:37

2 Answers 2

7

The initialization expression is not {1,0,0,1,1,0}

The initialization expression must be new short[6] { 1,1,1,1,1,1 }

So, essentially, the statement of your question is the answer to your question.

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

2 Comments

You could omit the length specifier though.
@ckuri yes, that's right, and preferable.
1

This syntax : short[] arr = {1, 0, 0, 1, 1, 0};
is called array initialization syntax and it works only in declaration.
why ?

As the guy here wrote, it just how Microsoft guys choose to implement for some reason.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.