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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With