Initialize a dictionary with values ​​in C # 2.0

In C # 2.0, we can initialize arrays and lists with values, such as:

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 that you can do this easily in C # 3.0 onwards:

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

But this does not work in C # 2.0. Is there any workaround for this without using Add or based on an existing collection?

+4
source share
1 answer

But this does not work in C # 2.0. Is there any workaround for this without using Add or based on an existing collection?

No. The closest I can think of would be to write my own DictionaryBuilder type to make it easier:

 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 one expression that is useful for the fields that you want to initialize at the point of declaration.

+10
source

Source: https://habr.com/ru/post/1492231/


All Articles