-2

I have a control which I can add some other controls in it. I need to add those controls in object initialization but it will give me an error that the Controls property is an indexer and it is read-only. so I should add in it in another line using the Add method. Is there any way to do such thing in object initialization?

pgvSections.Pages.Add(new PageView() { Name = sectionName, /* Controls = DOES NOT ALLOWED */  });
pgvSections.Pages.Last().Controls.Add(someControl);
Inside Man
  • 4,194
  • 12
  • 59
  • 119

1 Answers1

1

According to the documentation on GitHub linked by PetSerAl (kudos to him for pointing out my mistake), something like Controls = { new Control(), new Control(), ... } is allowed, because it automatically gets converted to a series of Controls.Add().

Servy
  • 202,030
  • 26
  • 332
  • 449
StackLloyd
  • 409
  • 2
  • 9
  • *There is no way to `Add` elements to a collection in an object initializer* Can you provide any reference to support your claim? It seems work fine for me: https://sharplab.io/#v2:C4LgTgrgdgPgAgBgARwIwG4CwAoRLUAsWuAzPgGwoBM+A7EgN45IsplqVwFICyAhgEsoACgCUjZqykBhJAGMkAXiRQApgHckshkgAyAgM7AljJKgA0SKpbIBfJLeJSpaAJzC0CAHQApAPZCwgBEliHyXvpGoqJOrLY48aTUWhLYLmSRwAA8QsAAfHqGxjoA5qrA6A4mapqZOVD5YsSJQA=== – user4003407 May 16 '19 at 16:00
  • That's suprising. In your example, that syntax appears to be automatically converted to `List.AddRange(new List() { 1, 2, 3 })`. I can't find any documentation regarding that, but nevertheless, it works, so I suppose nothing prevents the OP from doing something like `Controls = { new Control(), new Control(), ... }`. Thank you for sharing that, @PetSerAl. – StackLloyd May 16 '19 at 16:11
  • You can find specification [here](https://github.com/dotnet/csharplang/blob/master/spec/expressions.md#object-initializers). – user4003407 May 16 '19 at 16:29
  • Fantastic. Thank you very much. C# never stops to amaze me. – StackLloyd May 16 '19 at 20:26