3

Is it possible to do in this way (or maybe I need specific version of C#)?

Function<int,int,int,int> triSum = (a,b,c) => {return a+b+c;};
var tup = (1,2,3);
triSum(tup); //passing one tuple instead of multiple args

Update: I mean passing tuple instead of separate arguments.

public void DoWrite(string s1, string s2)
{
Console.WriteLine(s1+s2);
}
public (string,string) GetTuple()
{
//return some of them
}
//few lines later
DoWrite(GetTuple());
Troll the Legacy
  • 675
  • 2
  • 7
  • 22

3 Answers3

9

Yes you could use Named ValueTuples C# 7.1 , or even just a Local Method if it suits

Action<(int a, int b, int c)> triSum = t 
   => Console.WriteLine(t.a + t.b + t.c);

triSum((1, 2, 3));

or just as a local method

void TriSum((int a, int b, int c) t)
   => Console.WriteLine(t.a + t.b + t.c);

TriSum((1, 2, 3));
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
5

You can do this:

Func<(int a, int b, int c), int> triSum = x => { return x.a + x.b + x.c; };

var tup = (1, 2, 3);

var sum = triSum(tup);

Or more succinctly this:

Func<(int a, int b, int c), int> triSum = x => x.a + x.b + x.c;
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
1

There are some mistakes in the code, in short the following works:

Func<Tuple<int,int,int>,int > triSum = a => { return a.Item1 + a.Item2 + a.Item3; };
Tuple<int,int,int> tup = new Tuple<int, int, int>(3,4,5);
triSum(tup); //passing one tuple instead of multiple args

Problems in the code above:

  1. Action is a function delegate which returns void, so you should use Func
  2. The way you passed parameters to Action make them three independent ints and not a tuple
  3. Also the syntax var tup = (1,2) is from c# 7.0 onwards and cannot be used in older version (a nuget package is there though)
peeyush singh
  • 1,337
  • 1
  • 12
  • 23
  • 1. Thanks, fixed. 2. And that's a main question - passing valuetuple into places which waiting for separate arguments. 3. Not a problem. I mean maybe I need some C#8 or specific package etc. to achieve asked behavior? – Troll the Legacy Apr 09 '19 at 09:04
  • @TrolltheLegacy Each tuple is a different type, it is not possible for a compiler to substitute a number of ints with a tuple having same number of ints. You will have to modify the function definition to make it explicitly as a tuple – peeyush singh Apr 09 '19 at 09:07
  • And that's must be an answer. – Troll the Legacy Apr 09 '19 at 09:22