12

With the code below,

class Program
{
    static void Main(string[] args)
    {
        Tuple<int, int> test = TupleTest();

    }

    static (int, int) TupleTest()
    {
        return (1, 2);
    }

I am getting following compile time error.

Error CS0029 Cannot implicitly convert type '(int, int)' to 'System.Tuple < int, int >'

Does it mean the new version of Tuple is not compatible with the old version implicitly? Or am I doing something wrong here?

jim crown
  • 473
  • 3
  • 11
  • 6
    The "new tuple" is a different type called [`System.ValueTuple`](https://msdn.microsoft.com/en-us/library/system.valuetuple(v=vs.110).aspx) (see [this question](http://stackoverflow.com/questions/41084411/whats-the-difference-between-system-valuetuple-and-system-tuple) for a discussion of the differences) and AFAIK there are no plans to make it implicitly convertible to `System.Tuple` – UnholySheep Apr 23 '17 at 21:58
  • As Matej answered below you should use the extension methods (`ToTuple`). The reason those cannot be implemented as user-defined conversions is that we need them to go above arity 7. – Julien Couvreur May 28 '17 at 21:26

2 Answers2

18

Yeah, you should use extension method ToTuple. So in your example...

class Program
{
    static void Main(string[] args)
    {
        Tuple<int, int> test = TupleTest().ToTuple();

    }

    static (int, int) TupleTest()
    {
        return (1, 2);
    }
Matěj Pokorný
  • 16,977
  • 5
  • 39
  • 48
3
  • Use ValueTuple instead:

    ValueTuple<int, int> test = TupleTest();
    
  • Use the ToTuple extension method (ToValueTuple is also available):

    Tuple<int, int> test = TupleTest().ToTuple();
    
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632