Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are those extra curly brackets doing in C#?

Tags:

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?

like image 445
Jerry Nixon Avatar asked Oct 25 '11 19:10

Jerry Nixon


2 Answers

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

like image 29
Reed Copsey Avatar answered Sep 23 '22 20:09

Reed Copsey


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.

like image 184
Jon Skeet Avatar answered Sep 23 '22 20:09

Jon Skeet