Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# tuple deconstructor inside another tuple constructor

Tags:

c#

Is there C# feature to deconstruct tuple into subset fields of anoter tuple?

public (bool, int) f1() => (true, 1);
public (double, bool, int) f2 => (1.0, f1() /*!!here!!*/);

Thanks!

like image 510
Ilnar Gabidullin Avatar asked Aug 27 '20 08:08

Ilnar Gabidullin


Video Answer


1 Answers

There is currently no such C# feature, so you will have to write f2() as

public (double, bool, int) f2()
{
    var tuple = f1();
    return (1.0, tuple.Item1, tuple.Item2);
}

However if you really wanted to, you could write a helper class to combine tuples:

public static class TupleCombiner
{
    public static (T1, T2, T3) Combine<T1, T2, T3>(T1 item, (T2, T3) tuple)
    {
        return (item, tuple.Item1, tuple.Item2);
    }

    public static (T1, T2, T3) Combine<T1, T2, T3>((T1, T2) tuple, T3 item)
    {
        return (tuple.Item1, tuple.Item2, item);
    }

    // Etc for other combinations if needed
}

Then if you put using static YourNamespace.TupleCombiner; at the top of the code file your code would look like this:

public static (bool, int)         f1() => (true, 1);
public static (double, bool, int) f2() => Combine(1.0, f1());
public static (bool, int, double) f3() => Combine(f1(), 1.0);

Of course, this also works for var declarations inside methods:

public static void Main()
{
    var tuple = Combine(1.0, f1());
}

I'm not convinced this is in any way worth it, but it's an option.

Also note that - as pointed out by /u/Ry- in the comments - There is a proposal for tuple "splatting" on Github, but that proposal is over three years old (and it doesn't really seem to be exactly what you're asking for).

like image 92
Matthew Watson Avatar answered Oct 22 '22 00:10

Matthew Watson