What is C# analog of C++ std::pair?
Tuples are available since .NET4.0 and support generics:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
In previous versions you can use System.Collections.Generic.KeyValuePair<K, V>
or a solution like the following:
public class Pair<T, U> {
public Pair() {
}
public Pair(T first, U second) {
this.First = first;
this.Second = second;
}
public T First { get; set; }
public U Second { get; set; }
};
And use it like this:
Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);
This outputs:
test
2
Or even this chained pairs:
Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;
Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);
That outputs:
test
12
true
System.Web.UI
contained the Pair
class because it was used heavily in ASP.NET 1.1 as an internal ViewState structure.
Update Aug 2017: C# 7.0 / .NET Framework 4.7 provides a syntax to declare a Tuple with named items using the System.ValueTuple
struct.
//explicit Item typing
(string Message, int SomeNumber) t = ("Hello", 4);
//or using implicit typing
var t = (Message:"Hello", SomeNumber:4);
Console.WriteLine("{0} {1}", t.Message, t.SomeNumber);
see MSDN for more syntax examples.
Update Jun 2012: Tuples
have been a part of .NET since version 4.0.
Here is an earlier article describing inclusion in.NET4.0 and support for generics:
Tuple<string, int> t = new Tuple<string, int>("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.