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!
To get the custom initialization to work like Dictionary you need to support two things. Your type needs to implement
IEnumerableand have an appropriateAddmethod. You are initializing anArray, which doesn’t have anAddmethod. For exampleand then you can do