0

I am new in C#. I am following a video on a GUI framework. I wonder why there is not normal parenthesis '()' but curly parenthesis '{}' after the 'new Label' in the following code.

Are we not instantiating a class here?

Content = new Label {
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
    Text = "Hello word"
};
O. Altun
  • 685
  • 7
  • 20
  • 6
    The term to google is ["object initializer"](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers) – René Vogt Jul 07 '17 at 12:47
  • It is a one-liner shortcut to `new Label() { Property1 = value1, etc...};` the default parameterless constructor is called. – Cleptus Jul 07 '17 at 12:50

1 Answers1

1

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,
};
Alex
  • 37,502
  • 51
  • 204
  • 332