But it doesn't work in C# 2.0. Is there any workaround for this without using Add or basing on an already existing collection?
No. The closest I can think of would be to write your own DictionaryBuilder
type to make it simpler:
public class DictionaryBuilder<TKey, TValue>
{
private Dictionary<TKey, TValue> dictionary
= new Dictionary<TKey, TValue> dictionary();
public DictionaryBuilder<TKey, TValue> Add(TKey key, TValue value)
{
if (dictionary == null)
{
throw new InvalidOperationException("Can't add after building");
}
dictionary.Add(key, value);
return this;
}
public Dictionary<TKey, TValue> Build()
{
Dictionary<TKey, TValue> ret = dictionary;
dictionary = null;
return ret;
}
}
Then you can use:
Dictionary<string, int> x = new DictionaryBuilder<string, int>()
.Add("Foo", 10)
.Add("Bar", 20)
.Build();
This is at least a single expression still, which is useful for fields where you want to initialize at the point of declaration.