I have a scenario where I have a custom mapping class.
I would like to be able to create the new instance and declare data for it at the same time and implement a syntax similar to:
public static HybridDictionary Names = new HybridDictionary()
{
{People.Dave, "Dave H."},
{People.Wendy, "Wendy R."}
}
and so on. How do I define my class to enable this kind of syntax?
What you are trying to acheive is a Collection Initializer
Your HybridDictionary class need to implement IEnumerable<> and have an Add method like this:
public void Add(People p, string name)
{
....
}
Then your instanciation should work.
Note: By convention, the key should be the first parameter followed by the value (i.e. void Add(string key, People value).
Basically, you should implement ICollection<T>, but here is a more detailed explanation: http://blogs.msdn.com/madst/archive/2006/10/10/What-is-a-collection_3F00_.aspx.
In the article Mads Torgersen explains that a pattern based approach is used, so the only requirements is that you need to have a public Add method with the correct parameters and implement IEnumerable. In other words, this code is valid and works:
using System.Collections;
using System.Collections.Generic;
class Test
{
static void Main()
{
var dictionary = new HybridDictionary<string, string>
{
{"key", "value"},
{"key2", "value2"}
};
}
}
public class HybridDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
private readonly Dictionary<TKey, TValue> inner = new Dictionary<TKey, TValue>();
public void Add(TKey key, TValue value)
{
inner.Add(key, value);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return inner.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
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