Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate C# tuple values to match method arguments

Tags:

c#

.net

tuples

I am wondering is it possible to 'spread' tuple's values in a way to properly match method arguments.

For example:

public (int, object) GetTuple() {
   return (5, null);
}

public void ReceiveMultipleArguments(int a, object b) { ... }

The call of ReceiveMultipleArguments method like this:

ReceiveMultipleArguments(GetTuple());

will result in this error:

CS7036: There is no argument given that corresponds to the required formal parameter 'b' of 'Method1(int, object)'

The possible solution is to destructure tuple manually then provide each value as method argument, but is there a way to do it shorter, like spread operator that exists in javascript, for example?

like image 318
Dušan Avatar asked Nov 25 '25 07:11

Dušan


1 Answers

C# is a strongly typed language, so you cannot pass tuple (which has its own class ValueTuple class).

So, you could just define overload for the method:

public void Test()
{
    ReceiveMultipleArguments(GetTuple());
}

public (int, object) GetTuple()
{
    return (5, null);
}

public void ReceiveMultipleArguments((int a, object b) @params) => ReceiveMultipleArguments(@params.a, @params.b);
public void ReceiveMultipleArguments(int a, object b) { ... }
like image 102
Michał Turczyn Avatar answered Nov 26 '25 22:11

Michał Turczyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!