tags:

views:

117

answers:

2

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?

+2  A: 

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();
    }
}
driis
+6  A: 

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).

SelflessCoder
Correct. The compiler looks for a method called `Add()` with a matching set of arguments - and it requires the type implement IEnumerable or IEnumerable<T>. It's as simple as that.
LBushkin