I\'m interested: What is C#\'s analog of std::pair
in C++? I found System.Web.UI.Pair
class, but I\'d prefer something template-based.
Than
The PowerCollections library (formerly available from Wintellect but now hosted on Codeplex @ http://powercollections.codeplex.com) has a generic Pair structure.
Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
and access values through t.Item1
and t.Item2
, you can simply do it like that:
(string message, int count) = ("Hello", 4);
or even:
(var message, var count) = ("Hello", 4);
Unfortunately, there is none. You can use the System.Collections.Generic.KeyValuePair<K, V>
in many situations.
Alternatively, you can use anonymous types to handle tuples, at least locally:
var x = new { First = "x", Second = 42 };
The last alternative is to create an own class.
On order to get the above to work (I needed a pair as the key of a dictionary). I had to add:
public override Boolean Equals(Object o)
{
Pair<T, U> that = o as Pair<T, U>;
if (that == null)
return false;
else
return this.First.Equals(that.First) && this.Second.Equals(that.Second);
}
and once I did that I also added
public override Int32 GetHashCode()
{
return First.GetHashCode() ^ Second.GetHashCode();
}
to suppress a compiler warning.
I was asking the same question just now after a quick google I found that There is a pair class in .NET except its in the System.Web.UI ^ ~ ^ (http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) goodness knows why they put it there instead of the collections framework
C# has tuples as of version 4.0.