简体   繁体   中英

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

I have come across this code -

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

What does it mean? What actually is x ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM