Equivalent of Tuple (.NET 4) for .NET Framework 3.5

Otiel picture Otiel · Aug 19, 2011 · Viewed 41.6k times · Source

Is there a class existing in .NET Framework 3.5 that would be equivalent to the .NET 4 Tuple?

I would like to use it in order to return several values from a method, rather than create a struct.

Answer

Tomas Jansson picture Tomas Jansson · Aug 19, 2011

No, not in .Net 3.5. But it shouldn't be that hard to create your own.

public class Tuple<T1, T2>
{
    public T1 First { get; private set; }
    public T2 Second { get; private set; }
    internal Tuple(T1 first, T2 second)
    {
        First = first;
        Second = second;
    }
}

public static class Tuple
{
    public static Tuple<T1, T2> New<T1, T2>(T1 first, T2 second)
    {
        var tuple = new Tuple<T1, T2>(first, second);
        return tuple;
    }
}

UPDATE: Moved the static stuff to a static class to allow for type inference. With the update you can write stuff like var tuple = Tuple.New(5, "hello"); and it will fix the types for you implicitly.