4

I have come across this code -

(int, int) x = (10, 10);

What does it mean? What actually is x?

barbsan
  • 3,418
  • 11
  • 21
  • 28
naxbut
  • 43
  • 4
  • 2
    It's a [ValueTuple](https://learn.microsoft.com/en-us/dotnet/api/system.valuetuple?view=netframework-4.7.2) and this is a shorthand way of doing `ValueTuple x = new ValueTuple(10, 10)` – MindSwipe Mar 29 '19 at 06:47
  • 1
    https://stackoverflow.com/a/46602134/34092 may be worth a read. – mjwills Mar 29 '19 at 07:11

1 Answers1

8

What you have there is a ValueTuple:

A tuple is a data structure that has a specific number and sequence of elements. An example of a tuple is a data structure with three elements (known as a 3-tuple or triple) that is used to store an identifier such as a person's name in the first element, a year in the second element, and the person's income for that year in the third element.

They were introduced in C# 7.

Another way of writing it is like this:

ValueTuple<int, int> x = (10, 10);

or even:

ValueTuple<int, int> x = new ValueTuple<int, int>(10, 10);

You can access the values like so:

int val1 = x.Item1;
int val2 = x.Item2;

You can also alias them and then access the values by name:

(int A, int B) x = (10, 10); // or  var (A, B) = (10, 10);
int a = x.A;
int b = x.B;

You can read about how the ValueTuple aliases work over in this question.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86