C#: Index initializers in constructors, too?

Topics: C# Language Design
Nov 17, 2014 at 10:06 AM
Edited Nov 17, 2014 at 10:06 AM
I prefer to initialize objects through using constructors. This'll give the advantage to the programmer to know which fields to initialize. Using "post constructors", like curly initializers, the programmer not only has to perform a second step in order to create a valid object, she must also guess what's required to create a valid object.

So, here's my question: Will we get index initializers for constructors, too?
Nov 17, 2014 at 1:42 PM
The constructor is called that way because that's what constructs (builds) the object.

Everything needed to construct the object should be passed to the constructor.

Object initialization syntax is a easy to read and write way to initialize properties of the constructed object.

How do propose implementing index initializers for constructors?
Nov 18, 2014 at 11:40 AM
After some more reading through the specs I now learned that indexed initializers are not used to initialize an object itself but to add elements to a collection maintained by an object, which is a significant difference to using object initialization syntax for creating a valid object (a collection with zero elements is but a valid object).

So, yes, you are right, for the purpose of adding elements to a collection after creating a valid collection object this syntax is alright.

Case closed. I retract my question.
Nov 18, 2014 at 4:00 PM
Indexers are not necessarily related to collections. JSObject and it's not a collection. At least not in the traditional sense.

You'll be able to write:
var jso = new JSObject { ['P1'] = v1, ['P2'] = v2 };
instead of:
var temp new JSObject();
temp['P1'] = v1;
temp['P2'] = v2;
var jso = temp;
Nov 19, 2014 at 9:25 PM
Edited Nov 19, 2014 at 9:30 PM
Well, basically JSObject is nothing but a collection of Dictionaries. But what's more important: There's nothing that renders an JSObject "valid" or "invalid". In terms of object oriented programming, JSObject is but a late-binding, or - so to speak - "typeless", container, less more than a Variant or Object. At compile time and at run time it can be anything or nothing.

Index initializers, if I learned that correctly, are just syntactic sugar. They don't add new semantic to the language. - But that's what I was assuming when creating this thread.

Constructors are for creating valid objects at compile time. Something to call actions on and to retrieve properties from (or to update properties on in a later step if the object is supposed to mutate). - So I still believe there's no need to add an index initializer syntax to constructors. Semantically no signature of any constructor can render a container object valid by adding defined members to the collection. It just wouldn't make sense.

So I still back away from my first post.