Randall Flagg
Randall Flagg

Reputation: 5108

C# Syntax explanation

I saw a few days ago this syntax and wondered if someone could tell me how it is called, how does it work and where is it useful.

When I ask how does it work I mean that the Setters property is readonly(get), And the second is what do this braces mean: "Setters = {".

http://msdn.microsoft.com/en-us/library/ms601374.aspx

Thanks

datagrid.CellStyle = new Style(typeof(DataGridCell))
                {
                    // Cancel the black border which appears when the user presses on a cell
                    Setters = { new Setter(Control.BorderThicknessProperty, new Thickness(0)) } // End of Setters
                } // End of Style

Upvotes: 1

Views: 260

Answers (3)

EKS
EKS

Reputation: 5623

It seems to be setting default values when the object is being made. This is kind of like passing values to the constructor, but you aren't limited to just the options the constructor gives you.

Upvotes: 0

Tomas Petricek
Tomas Petricek

Reputation: 243051

It is call object initializer and collection initializer and it allows you to set properties in the { .. } block when calling a constructor. Inside the block, you're using Setters = { ... } which is a collection initializer - it allows you to specify elements of a collection (here, you don't have to create a new instance of the collection - it just adds elements in curly braces). For more information see this MSDN page.

In general, the syntax of object initializers has a few options:

// Without explicitly mentioning parameter-less constructor:
new A { Prop1 = ..., Prop2 = ... }
// Specifying constructor arguments:
new A(...) { Prop1 = ..., Prop2 = ... }

The syntax for collection initializers looks like this:

// Creating new instance
new List<int> { 1, 2, 3 }
// Adding to existing instance inside object initializer:
SomeList = { 1, 2, 3 }

It is worth mentioning that this is closely related to anonymous types (where you don't give a type name - the compiler generates some hidden type and you can work with it using var):

// Create anonymous type with some properties
new { Prop1 = ..., Prop2 = ... }

All of these features are new in C# 3.0. See also this SO post which explains some tricky aspect of collection initializers (in the style you're using them).

Upvotes: 9

Adeel
Adeel

Reputation: 19228

instantiated the new object Style, and than setting its property Setters It's a c# 3.0 feature.

Upvotes: 0

Related Questions