8

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?

gunr2171
  • 16,104
  • 25
  • 61
  • 88
nix86
  • 2,837
  • 11
  • 36
  • 69
  • 3
    That is a normal C# 3.0 (or higher) object initialization expression. See http://msdn.microsoft.com/en-us/library/vstudio/bb738566.aspx for more information. – Kris Vandermotten Sep 12 '14 at 13:10
  • There's no difference between the two in terms of functionality. – Casey Sep 12 '14 at 13:14
  • 1
    Also, you can omit the parenthesis for the constructor **only** if there is a parameterless constructor (or none) for that object. If there are constructors which take parameters, they can be combined with object initializers. The syntax `new Person("John", "Smith") { Address = "123 Main Street" }` is also valid. – ardila Sep 12 '14 at 13:26
  • @emodendroket Actually, there is. See my answer. – Kris Vandermotten Sep 12 '14 at 13:28
  • @KrisVandermotten OK, fair enough. – Casey Sep 12 '14 at 14:13

2 Answers2

8

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.

Kris Vandermotten
  • 10,111
  • 38
  • 49
3

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.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278