Reputation: 3047
Studying Xamarin I've come across this kind of use of curly braces:
Label header = new Label
{
Text = "Label",
Font = Font.BoldSystemFontOfSize(50),
HorizontalOptions = LayoutOptions.Center
};
And I'm wondering how it can be correct because usually in C# when I want to create an instance of an object I do:
Label label = new Label();
label.Text = "Label";
...
What kind of use of curly brackets is this? How can you create an object without round brackets?
Upvotes: 8
Views: 5882
Reputation: 10201
That 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 former, when setting the value of a property causes an exception, the variable header
is not assigned, while as in the latter it is. The reason is that the former is equivalent to:
Label temp = new Label();
temp.Text = "Label";
Label label = temp;
As you can see, if there is an exception in the second line, the third line never gets executed.
Upvotes: 8
Reputation: 54127
This is just a different syntax for initializing the properties of an object, called object initializer syntax. It's useful as a way to tell a future developer "this object isn't ready until these properties are set".
This syntax was one of the new features in C# 3.0, which may be why you're not familiar with it.
Upvotes: 3