This project is read-only.
5

Resolved

Array initializers in property initializers

description

class C {
    public int[] Array { get; } = { 1, 2 };
}
Currently this does not compiles.
While this is rarely-used feature, I'm expecting conformity with field/variable initializers here.

comments

TomasMatousek wrote Aug 3, 2014 at 8:11 AM

This doesn't work for field initializers either. You need to add "new int[]" or "new[]"

class C {
public int[] Array { get; } = new[] { 1, 2 };
}

ControlFlow wrote Aug 5, 2014 at 10:55 AM

Seriously? Well, let's learn some C# 1.0 grammar then! Local variables:
declaration-statement:
  local-variable-declaration   ;
  local-constant-declaration   ;

local-variable-declaration:
  type   local-variable-declarators

local-variable-declarators:
  local-variable-declarator
  local-variable-declarators   ,   local-variable-declarator

local-variable-declarator:
  identifier
  identifier   =   local-variable-initializer

local-variable-initializer:
  expression
  array-initializer   <===============
Field declarations:
field-declaration:
  attributes   field-modifiers   type   variable-declarators   ;

variable-declarators:
  variable-declarator
  variable-declarators   ,   variable-declarator

variable-declarator:
  identifier
  identifier   =   variable-initializer

variable-initializer:
  expression
  array-initializer     <===============
Let's have a look what array-initializer is:
array-initializer:
  {   variable-initializer-listopt   }
  {   variable-initializer-list   ,   }

variable-initializer-list:
  variable-initializer
  variable-initializer-list   ,   variable-initializer

variable-initializer:
  expression
  array-initializer
Wow, looks like this is valid C#:
class C {
    readonly int[] _xs = { 1, 2, 3, 4 };
    
    public void M() {
        int[] ys = { 5, 6, 7, 8 };
    }
}
And it compiles with Roslyn.

angocke wrote Aug 6, 2014 at 5:41 PM

Yup, this looks valid to me, I just haven't gotten around to fixing it yet :/

angocke wrote Nov 25, 2014 at 1:53 AM

Fixed in 73a206ceb