Is there a way in c# to deconstruct a tuple and pass the values in one line?

55 Views Asked by At

assume the following simple code:

public (string, string) GetTuple()
{
    return ( "a", "b" );
}

public string DoSomethingWithStrings(string str1, string str2) => 
    str1 + str2;

public void Example1( )
{
    var (a, b) = GetTuple();

    var r = DoSomethingWithStrings( a, b );

    //not working
    //var r = DoSomethingWithStrings( GetTuple() );
}

Is there some syntatic sugar, an extension method or something, to make the compiler understand the last commented code line?

Im using a Pipe extension method, so my goal is, instead of

public void Example2()
{
    var t =
        GetTuple()
        .Pipe(
            t =>
                DoSomethingWithStrings( t.Item1, t.Item2 )
        );
}

I want

public void Example3()
{
    var t =
        GetTuple()
        .Pipe(
            ( a, b ) =>
                DoSomethingWithStrings( a, b )
        );
}

My best take is:

public static TResult Pipe<TInput, TResult>(
    this TInput input,
    Func<TInput, TResult> pipeFunc 
) => 
    pipeFunc( input );

public static TResult Pipe<TInput1, TInput2, TResult>(
    this (TInput1, TInput2) input,
    Func<TInput1, TInput2, TResult> pipeFunc
) =>
    input
    .Pipe(
        t => pipeFunc( t.Item1, t.Item2 )
    );

Needless to say that this will get very messy, if I want to do this for all kinds of tuple item counts.

0

There are 0 best solutions below