I want to use a collection initializer for the next bit of code:
public Dictionary GetNames()
{
Dictionary names =
The question is tagged c#-3.0, but for completeness I'll mention the new syntax available with C# 6 in case you are using Visual Studio 2015 (or Mono 4.0):
var dictionary = new Dictionary
{
[1] = "Adam",
[2] = "Bart",
[3] = "Charlie"
};
Note: the old syntax mentioned in other answers still works though, if you like that better. Again, for completeness, here is the old syntax:
var dictionary = new Dictionary
{
{ 1, "Adam" },
{ 2, "Bart" },
{ 3, "Charlie" }
};
One other kind of cool thing to note is that with either syntax you can leave the last comma if you like, which makes it easier to copy/paste additional lines. For example, the following compiles just fine:
var dictionary = new Dictionary
{
[1] = "Adam",
[2] = "Bart",
[3] = "Charlie",
};