Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Dictionary-style collection initializer on custom class [duplicate]

Tags:

c#

dictionary

Possible Duplicate:
Custom Collection Initializers

I have a simple Pair class:

public class Pair<T1, T2>
    {
        public Pair(T1 value1, T2 value2)
        {
            Value1 = value1;
            Value2 = value2;
        }

        public T1 Value1 { get; set; }
        public T2 Value2 { get; set; }
    }

And would like to be able to define it like a Dictionary object, all inline like so:

var temp = new Pair<int, string>[]
        {
            {0, "bob"},
            {1, "phil"},
            {0, "nick"}
        };

But it is asking me to define a full new Pair(0, "bob") etc, how would I implement this?

As usual, thanks guys!

like image 532
Chris Surfleet Avatar asked Mar 05 '12 16:03

Chris Surfleet


2 Answers

To get the custom initialization to work like Dictionary you need to support two things. Your type needs to implement IEnumerable and have an appropriate Add method. You are initializing an Array, which doesn't have an Add method. For example

class PairList<T1, T2> : IEnumerable
{
    private List<Pair<T1, T2>> _list = new List<Pair<T1, T2>>();

    public void Add(T1 arg1, T2 arg2)
    {
        _list.Add(new Pair<T1, T2>(arg1, arg2));
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _list.GetEnumerator();
    }
}

and then you can do

var temp = new PairList<int, string>
{
    {0, "bob"},
    {1, "phil"},
    {0, "nick"}
};
like image 198
Yuriy Faktorovich Avatar answered Sep 23 '22 02:09

Yuriy Faktorovich


Why not use a class that inherits from Dictionary?

public class PairDictionary : Dictionary<int, string>
{
}

private static void Main(string[] args)
{
    var temp = new PairDictionary
    {
        {0, "bob"},
        {1, "phil"},
        {2, "nick"}
    };

    Console.ReadKey();
}

You could also create your own collection (I suspect it is the case because you have the same Value1 for two items, so T1 doesn't act as a key in your example) that do not inherit from Dictionary.

If you want to use the syntactic sugar of collection initializer, you would have to provide a Add method that takes 2 arguments (T1 and T2 which are int and string in your case).

public void Add(int value1, string value2)
{
}

See Custom Collection Initializers

like image 8
ken2k Avatar answered Sep 23 '22 02:09

ken2k