5

In C# 2.0 we can initialize arrays and lists with values like this:

int[] a = { 0, 1, 2, 3 }; int[,] b = { { 0, 1 }, { 1, 2 }, { 2, 3 } }; List<int> c = new List<int>(new int[] { 0, 1, 2, 3 }); 

I would like to do the same with Dictionary. I know you can do it easily in C# 3.0 onwards like this:

Dictionary<int, int> d = new Dictionary<int, int> { { 0, 1 }, { 1, 2 }, { 2, 3 } }; 

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?

3
  • 4
    What's constraining you to still use C# 2? Life is so much better from C# 3 onwards, even if you're targeting .NET 2, that it's worth trying to muse a more recent compiler... Commented Jul 19, 2013 at 6:04
  • Ha ha, I was wondering if I should ask for not answering the way you did. Working with C# 2 is a requirement which I can't do much about. I know newer C# versions make things easier, but since I already ran into this problem, I figured I would ask out of curiosity. Commented Jul 19, 2013 at 6:10
  • I'm intrigued as to why there's this requirement though. Being limited to .NET 2.0 I can understand, but C# 2 seems an odder requirement. Commented Jul 19, 2013 at 6:13

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Skeet, your fluent syntax wouldn't work because Add doesn't return this;.
@Mechanical Object: Thanks for fixing the quote, but please don't change the semantics of code in other people's answers without checking first. I very deliberately have the code the way it is: I would consider it an error to add the same key multiple times; I don't want to silently ignore it. (An alternative would be to use the indexer, which would just overwrite the old entry instead - again, that would be silently hiding a problem though.)
You forgot to add return this again, fixed that :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.