Reputation: 31831
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
Reputation: 31651
The first curly brace set is the object initializer. The second set is an IList of names (collection).
Upvotes: 2
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
Reputation: 564851
This is a collection initializer. It's allowing you to add items to the Names
collection.
Upvotes: 11
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