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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With