This is an object initializer - introduced in C# 3.0
Content = new Label {
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Text = "Hello word"
};
Will only work if Label
has a parameterless constructor.
We can assume Label
looks something like this:
public class Label
{
public Label()
{
//this empty ctor is not required by the compiler
//just here for illustration
}
public string HorizontalOptions {get;set}
public string VerticalOptions {get;set}
public string Text {get;set}
}
The object initializer is setting the properties, when it's instantiated.
If, however, Label
did have a parameter in the ctor, like this:
public class Label
{
public Label(string text)
{
Text = text
}
public string HorizontalOptions {get;set}
public string VerticalOptions {get;set}
public string Text {get;set}
}
then this would be equivalent
Content = new Label("Hello World") { //notice I'm passing parameter to ctor here
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
};