Using curly braces with object constructs
While researching Xamarin I came across this use of curly braces:
Label header = new Label
{
Text = "Label",
Font = Font.BoldSystemFontOfSize(50),
HorizontalOptions = LayoutOptions.Center
};
And I am wondering how this could be correct, because usually in C # when I want to instantiate an object I am doing:
Label label = new Label();
label.Text = "Label";
...
What use of curly braces is this? How do I create an object without parentheses?
source to share
This is a normal C # 3.0 (or higher) object initialization expression. See http://msdn.microsoft.com/en-us/library/bb397680.aspx and http://msdn.microsoft.com/en-us/library/vstudio/bb738566.aspx for more information .
There is a subtle difference between
Label header = new Label
{
Text = "Label",
};
and
Label label = new Label();
label.Text = "Label";
In the first case, when setting the property value, an exception is thrown, the variable is header
not assigned, while in the latter it is. The reason is that the first is equivalent to:
Label temp = new Label();
temp.Text = "Label";
Label label = temp;
As you can see, if there is an exception on the second line, the third line will never be executed.
source to share
It's just another syntax for initializing object properties called object initializer syntax . This is useful as a way to tell a future developer "this object is not ready until these properties are set".
This syntax was one of the new features in C # 3.0 , so you may not be familiar with it.
source to share