Jerry Nixon
Jerry Nixon

Reputation: 31831

What are those extra curly brackets doing in C#?

I have no idea how to search for this question; forgive me if it's redundant.

So, I have some code like this:

textBox1.InputScope = new InputScope { Names = { _Scope } };

The Names property is of type IList

Is my code adding an item to a list or creating a new list?

What's that extra curly bracket doing?

Upvotes: 9

Views: 1810

Answers (4)

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31651

The first curly brace set is the object initializer. The second set is an IList of names (collection).

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1064104

new InputScope { // indicates an object-initializer for InputScope using
                 // the default constructor
   Names = { // indicates an in-place usage of a collection-initializer
     _Scope  // adds _Scope to Names
   } // ends the collection-initializer
}; // ends the object-initializer

i.e.

var tmp = new InputScope();
tmp.Names.Add(_Scope);
textBox1.InputScope = tmp;

Upvotes: 7

Reed Copsey
Reed Copsey

Reputation: 564851

This is a collection initializer. It's allowing you to add items to the Names collection.

Upvotes: 11

Jon Skeet
Jon Skeet

Reputation: 1503449

This is a collection initializer, but one which isn't creating a new collection - it's just adding to an existing one. It's used as the initializer-value part of a member-initializer within an object-initializer. It's the equivalent of:

InputScope tmp = new InputScope();
tmp.Names.Add(_Scope);
textBox1.InputScope = tmp;

See section 7.6.10.3 of the C# 4 spec for more infomation.

Upvotes: 15

Related Questions