Search code examples
c#.net-3.5tuples

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


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.


Solution

  • 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.