Proposal: Brace type initializers #2492
Replies: 9 comments
-
Why? What's the advantage? Just saving some typing? |
Beta Was this translation helpful? Give feedback.
-
One possible improvement could be to distinguish the creation of immutable object (sealed poco class with get and private set only) vs mutable objects. Type { }; could be used for mutable (collections initializer form) and yes, the other minor advantage would be less "new" around the code, |
Beta Was this translation helpful? Give feedback.
-
Except C# already distinguishes the two types of braces when creating objects for completely different purpose:
I don't think adding a new syntax for creating objects where the two types of braces have a completely different meaning (and one that is not enforced at that) would be a good idea. |
Beta Was this translation helpful? Give feedback.
-
I love C++11 initializers but I normally write them as auto r1 = SomeType { 15, "a parameter", "another parameter", 0 }; because it makes for nicely regular alignment. That said, one of the primary reasons for the introduction of uniform initialization syntax in C++ was to improve type safety of construction. This isn't an issue in C#. As for
This proposal won't help here because immutable pocos can already be constructed with constructors and factories. The desire for immutable initializers is to combine the significant readability benefits of C# object initializers without requiring |
Beta Was this translation helpful? Give feedback.
-
To clarify, I think that what C# needs in this area is var p = new Person
{
Name = "John",
Age = 12
} where |
Beta Was this translation helpful? Give feedback.
-
We already have: var p = new Person
(
Name: "John",
Age: 12
); Records will encourage this approach. |
Beta Was this translation helpful? Give feedback.
-
@svick , @aluanhaddad Since @HaloFour cited the record feature, there's now no more mismatch with collections initializers. |
Beta Was this translation helpful? Give feedback.
-
please see my EDIT 2 at the original proposal, for better clarification of what I think may be useful. |
Beta Was this translation helpful? Give feedback.
-
I guess it would be nice if new operator could be optionally avoided (when possible) in favour of object initialization in the c++ 11/14 style, something like..
http://www.stroustrup.com/C++11FAQ.html#uniform-init
msdn initialization
c++ initialization
is this doable or any useful at all, what do you think?
EDIT:
EDIT 2 (for better clarity):
let's start with an immutable type (sealed poco class with only get methods)
proposed changes would make possible to turn this "old" one (just an example class, sorry if it's not too clear) ...
into this "new one"...
please notice the use of member initializer list which is now made possible
How does it feel?
Beta Was this translation helpful? Give feedback.
All reactions