Can I use a collection initializer for Dictionary<TKey, TValue> entries?

Gerrie Schenck picture Gerrie Schenck · Jan 30, 2009 · Viewed 38.8k times · Source

I want to use a collection initializer for the next bit of code:

public Dictionary<int, string> GetNames()
{
    Dictionary<int, string> names = new Dictionary<int, string>();
    names.Add(1, "Adam");
    names.Add(2, "Bart");
    names.Add(3, "Charlie");
    return names;
}

So typically it should be something like:

return new Dictionary<int, string>
{ 
   1, "Adam",
   2, "Bart"
   ...

But what is the correct syntax for this?

Answer

bruno conde picture bruno conde · Jan 30, 2009
var names = new Dictionary<int, string> {
  { 1, "Adam" },
  { 2, "Bart" },
  { 3, "Charlie" }
};