-
Notifications
You must be signed in to change notification settings - Fork 4.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Proposal: Initialize to known type instead of anonymous type when possible #16769
Comments
Akin to #35. |
The following two mean very different things: var p1 = new PointWrapper {
Value = { X = 1, Y = 2 }
};
var p2 = new PointWrapper {
Value = new Point { X = 3, Y = 4 }
}; They mean the following: PointWrapper p1 = new PointWrapper();
p1.Value.X = 1;
p1.Value.Y = 2;
PointWrapper p2 = new PointWrapper();
Point temp = new Point();
temp.X = 3;
temp.Y = 4;
p2.Value = temp; The difference becomes very apparent when the property is readonly or is not initialized to a value. For example, if |
@HaloFour Then this "child" object initializer is a potentially dangerous but valid construct, without generating any warning/error. Don't know why was it introduced in the first place. I know there is a workaround to make it work. But I think this construct should be made safe without requiring that workaround, in 3 steps-
|
It was introduced specifically to allow initializing readonly properties. That behavior is shipped and cannot be changed.
Initializers cannot initialize readonly properties, for many reasons. Assuming that the property is actually some 1:1 match to a field, that field is As for record types, you would initialize them via the constructor, not their properties. |
Making initializers work with read-only properties is another discussion, IMHO. In this thread, I think we can stick to the main proposal, initialize to known type instead of anonymous type when possible. |
This was discussed as part of the "target-typed new" proposal (dotnet/csharplang#100). |
Given following classes-
the statement
is already valid. No need to specify type of property
Value
within the initializer. Evennew
keyword is not required (usingnew
is an error actually). ButPoint p = new { X = 1, Y = 2 };
is not valid. We have to writeMy proposal is, when the type of an object is known, make the type-name optional with initializers. In other words, convert the right hand anonymous typed object to the specified type enabling-
It should not affect the case when the type is not already known or specified like-
Same goes for collection initializers, so that this-
can be written like-
Related- #16648
The text was updated successfully, but these errors were encountered: