Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 767
nix86 Avatar asked Sep 12 '14 13:09

nix86


People also ask

What is a curly brace used for?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.

What is {} called in programming?

Brackets, or braces, are a syntactic construct in many programming languages. They take the forms of "[]", "()", "{}" or "<>." They are typically used to denote programming language constructs such as blocks, function calls or array subscripts. Brackets are also known as braces.

Which loops require curly braces?

If the number of statements following the for/if is single you don't have to use curly braces. But if the number of statements is more than one, then you need to use curly braces.

What is a curly brace called?

Parentheses resemble two curved vertical lines: ( ). A single one of these punctuation marks is called a parenthesis. It is considered a grammar error to only use a single parenthesis; parentheses are always used in pairs in proper grammar.


1 Answers

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.

like image 198
Kris Vandermotten Avatar answered Sep 28 '22 05:09

Kris Vandermotten