Allow Object Initializer to Support Both Properties and Children #4622
Unanswered
hollyschilling
asked this question in
Language Ideas
Replies: 1 comment 4 replies
-
var stack1 = new StackLayout
{
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color. Fuchsia,
Children = {
new Label { Text = "First" },
new Label { Text = "Second" }
}
}; |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Currently in C#, an object initializer may contain properties or children, as in either of these cases:
In modern UI code, it is common to have objects that have children and values to be set on them. For example, a StackLayout in Xamarin.Forms may have a
BackgroundColor
,Orientation
, and aHeightRequest
, in addition to its child views added to it. Currently, the only way to achieve this is through writing the code procedurally, such as:What I propose is that the syntax should be able to handle both, as the following:
This is a natural extension of the current functionality and should be fairly simple to implement. The only issue I could imagine is potential conflicts in cases of scope collisions.
In this example,
Header = new Label { Text = "Where does this go?" }
could be intended to assign to the property onFoo
or onBar
. If it is intended to assign to the property onFoo
, it would trigger the normal property setter onFoo
and ignore the property setter onBar
. If it instead were intended to assign to the property onBar
, it would trigger the property setter onBar
and then trigger theAdd
method onFoo
due to the associativity of the assignment operator. Even now, I'm not quite sure how C# 9 resolves this conflict.Since this is not a new problem and already has defined behavior, I do not see this as an impediment to implementation of this change.
Beta Was this translation helpful? Give feedback.
All reactions