Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a constructor with inline initialization for a custom map class?

Tags:

c#

.net

.net-3.5

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?

like image 895
MedicineMan Avatar asked Jan 07 '10 18:01

MedicineMan


2 Answers

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

like image 172
Jeff Cyr Avatar answered Nov 02 '22 17:11

Jeff Cyr


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();
    }
}
like image 38
driis Avatar answered Nov 02 '22 16:11

driis