Search code examples
c#curly-brackets

Use of curly braces with object construction


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?


Solution

  • 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.