make_pair in C#

posted @ Tuesday, November 23, 2004 11:28 PM

 

Recently in the C# forum on the Code Project someone asked of a mechanism to implement a make_pair in C#. make_pair is provided in the Standard Template Library in C++ which allows you to easily maintain a pair of two specified types in one contained data element. While there are classes in place within the .NET Framework version 1.1 that allow you to perform similar operations, basically any class that implements the IDictionary interface provides this base functionality that make_pair exposes (i.e, Hashtable, HybridDictionary, ListDictionary, etc) although access to their members isn't as direct as a make_pair exposes. While that doesn't raise the level of difficulty, lets look at another option. When we look at what version 2.0 of the .NET Framework provides in terms of generics, we can easily implement a make_pair in C#. The following is an example I put together that will run under version 2.0.

public class make_pair<T1, T2>
{
public T1 first
{
get {return this.t1;}
set {this.t1 = value;}
}

public T2 second
{
get { return this.t2; }
set { this.t2 = value; }
}

public make_pair(T1 type1, T2 type2)
{
this.t1 = type1;
this.t2 = type2;
}
private T1 t1;
private T2 t2;
}

Now that we have that defined we can use it like this:

make_pair<int, int> mpi = new make_pair<int, int>(5, 10);
Console.WriteLine("1st:{0}\n2nd:{1}", mpi.first, mpi.second);
mpi.first = 50;
mpi.second = 25;
Console.WriteLine("1st:{0}\n2nd:{1}", mpi.first, mpi.second);