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

Solution 1:

var names = new Dictionary<int, string> {
  { 1, "Adam" },
  { 2, "Bart" },
  { 3, "Charlie" }
};

Solution 2:

The syntax is slightly different:

Dictionary<int, string> names = new Dictionary<int, string>()
{
    { 1, "Adam" },
    { 2, "Bart" }
}

Note that you're effectively adding tuples of values.

As a sidenote: collection initializers contain arguments which are basically arguments to whatever Add() function that comes in handy with respect to compile-time type of argument. That is, if I have a collection:

class FooCollection : IEnumerable
{
    public void Add(int i) ...

    public void Add(string s) ...

    public void Add(double d) ...
}

the following code is perfectly legal:

var foos = new FooCollection() { 1, 2, 3.14, "Hello, world!" };