So I have to design a class that works on a collection of paired objects. There is a one-to-one mapping between objects. I expect the client of the class to have established this mapping before using my class.
My question is what is the best way to allow the user of my class to give me that information?
Is it to ask for a collection of pairs like this?
MyClass(IEnumerable<KeyValuePair<Object, Object>> objects)
Or seperate collections like this?
MyClass(IEnumberable<Object> x, IEnumerable<Object> y)
Or is there another option?
I like the first because the relationship is explicit, I don't like it because of the extra work it puts on the client.
I like the second because the types are more primitive and require less work, I don't like it because the mapping is not explicit. I have to assume the order is correct.
Opinions please?
In .NET 4 you should be using Tuple<T1,T2>
. More info on the Tuple class at MSDN.
If you have access to it, use Tuple<T, R>
. If you don't, just write a generic Tuple
or Pair
class of your own. I would avoid using KeyValuePair
, just because it's verbose and has an association with Dictionary
.
I would prefer KeyValuePair of the two you mention as it's more expressive and keeps the relationship between the objects.
But I would rather create a class which holds a reference to your pair. This is more readable in my opinion, and it never hurts to create an extra class or struct to express your actual actions.
(Pseudo-code)
class MyPair
{
public TypeA One;
public TypeB Two;
}
MyClass(IEnumerable<MyPair> objects)
There's mention of Tuple<,>
in some answers, which is as readable as KeyValuePair, but more flexible as it can contain more than two parameters.
[Edit - more indepth about Tuples/classes after a good nights sleep]
To Tuple or Not To Tuple
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