Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (datatype, datatype) x = (value, value) mean in C#? What is the actual data type of x?

Tags:

c#

.net

I have come across this code -

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

What does it mean? What actually is x?

like image 862
naxbut Avatar asked Jan 26 '23 13:01

naxbut


1 Answers

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.

like image 128
DiplomacyNotWar Avatar answered Feb 12 '23 19:02

DiplomacyNotWar