C # Tuple VS ValueTuple (tuples VS value tuples ),

Source: Internet
Author: User

C # Tuple VS ValueTuple (tuples VS value tuples ),

C #7.0 has come out for a while. We all know that the new feature has an optimization for tuples: ValueTuple. Here we will use detailed examples to illustrate Tuple VS ValueTuple (tuples VS value tuples), so that you can learn more about the benefits and usage of ValueTuple in 10 minutes.

If you are familiar with Tuple, you can skip the chapter "review Tuple" and go to the Chapter "ValueTuple details" to view the elegant usage of the value tuples.

 

Review Tuple

Tuple is a new feature in C #4.0 and is available in. Net Framework 4.0 or later versions.

A tuple is a data structure with a specific number and element sequence. For example, a triple data structure is designed to store student information. It contains three elements: the first element is the name, the second element is the age, and the third element is the height.

The usage of tuples is as follows:

1. How to Create tuples

By default,. Net Framework tuples only support 1 to 7 tuples. If there are 8 or more elements, use the nested Tuple and Rest attributes. In addition, the Tuple class provides static methods for creating tuples.

  • Create tuples using constructors:
var testTuple6 = new Tuple<int, int, int, int, int, int>(1, 2, 3, 4, 5, 6);Console.WriteLine($"Item 1: {testTuple6.Item1}, Item 6: {testTuple6.Item6}");var testTuple10 = new Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>>(1, 2, 3, 4, 5, 6, 7, new Tuple<int, int, int>(8, 9, 10));Console.WriteLine($"Item 1: {testTuple10.Item1}, Item 10: {testTuple10.Rest.Item3}");
  • The Tuple static method is used to construct tuples. A maximum of eight elements are supported:
var testTuple6 = Tuple.Create<int, int, int, int, int, int>(1, 2, 3, 4, 5, 6);Console.WriteLine($"Item 1: {testTuple6.Item1}, Item 6: {testTuple6.Item6}");var testTuple8 = Tuple.Create<int, int, int, int, int, int, int, int>(1, 2, 3, 4, 5, 6, 7, 8);Console.WriteLine($"Item 1: {testTuple8.Item1}, Item 8: {testTuple8.Rest.Item1}");

Note: The Tuple type constructed here is actually Tuple <int, int, Tuple <int>, therefore, the data type obtained by testTuple8.Rest is Tuple <int>. Therefore, the Item1 attribute must be used to obtain the exact value.

2. indicates a group of data

The following table creates a tuples to indicate the three information of a student: name, age, and height, instead of creating an additional class.

var studentInfo = Tuple.Create<string, int, uint>("Bob", 28, 175);Console.WriteLine($"Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]");
3. Return multiple values from the method

When a function needs to return multiple values, you can usually use the out parameter. Here, you can use tuples instead of out to return multiple values.

static Tuple<string, int, uint> GetStudentInfo(string name){    return new Tuple<string, int, uint>("Bob", 28, 175);}
static void RunTest(){ var studentInfo = GetStudentInfo("Bob"); Console.WriteLine($"Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]");}

4. multi-value transfer for Single-parameter Methods

When function parameters are only of the Object type, you can use tuples to transmit multiple parameter values.

static void WriteStudentInfo(Object student){    var studentInfo = student as Tuple<string, int, uint>;    Console.WriteLine($"Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]");}
static void RunTest(){ var t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(WriteStudentInfo)); t.Start(new Tuple<string, int, uint>("Bob", 28, 175)); while (t.IsAlive) { System.Threading.Thread.Sleep(50); }}

 

Although tuples have the preceding easy-to-use methods, they also have obvious shortcomings:

  • When accessing an element, you can only access it through ItemX. before using it, you must specify the element sequence. The attribute name has no practical meaning and is not easy to remember;
  • There can be a maximum of eight elements. To do more, you can only use the last element for nested extension;
  • Tuple is a reference type. It is not a value type like other simple types. It allocates space on the stack, and there may be too much creation and allocation work during CPU intensive operations.

Therefore, a new ValueTuple type is introduced in C #7.0. For details, see the following section.

ValueTuple

ValueTuple is one of the new features of C #7.0 and is available in. Net Framework 4.7 or later versions.

The value tuples are also a data structure used to indicate a specific number and element sequence, but they are different from those of the element group class. The main differences are as follows:

  • The value tuples are structure, value type, not class, And Tuple is class and reference type;
  • The value element is variable, not read-only, that is, the element value in the value element can be changed;
  • The data member of the value tuples is a field that is not a property.

The usage of value tuples is as follows:

1. How to Create a value tuples

Same as the group class ,. net Framework value tuples only support 1 to 7 tuples. If there are 8 or more elements, you need to use the nested and Rest attributes of the value tuples. In addition, the ValueTuple class can provide static methods for creating value tuples.

  • Create tuples using constructors:
var testTuple6 = new ValueTuple<int, int, int, int, int, int>(1, 2, 3, 4, 5, 6);Console.WriteLine($"Item 1: {testTuple6.Item1}, Item 6: {testTuple6.Item6}"); var testTuple10 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int, int>>(1, 2, 3, 4, 5, 6, 7, new ValueTuple <int, int, int>(8, 9, 10));Console.WriteLine($"Item 1: {testTuple10.Item1}, Item 10: {testTuple10.Rest.Item3}");
  • The Tuple static method is used to construct tuples. A maximum of eight elements are supported:
var testTuple6 = ValueTuple.Create<int, int, int, int, int, int>(1, 2, 3, 4, 5, 6);Console.WriteLine($"Item 1: {testTuple6.Item1}, Item 6: {testTuple6.Item6}"); var testTuple8 = ValueTuple.Create<int, int, int, int, int, int, int, int>(1, 2, 3, 4, 5, 6, 7, 8);Console.WriteLine($"Item 1: {testTuple8.Item1}, Item 8: {testTuple8.Rest.Item1}");

Note that the constructed Tuple type is actually Tuple <int, Tuple <int>, therefore, the data type obtained by testTuple8.Rest is Tuple <int>. Therefore, the Item1 attribute must be used to obtain the exact value.

Differences: After constructing a value tuples with more than 7 elements, you can use the following ItemX to access the values in the nested tuples. In the preceding example, you need to access the tenth element, you can use testTuple10.Rest. you can also access Item3 through testTuple10.Item10.

var testTuple10 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int, int, int>>(1, 2, 3, 4, 5, 6, 7, new ValueTuple<int, int, int>(8, 9, 10));Console.WriteLine($"Item 10: {testTuple10.Rest.Item3}, Item 10: {testTuple10.Item10}");
2. indicates a group of data

Create a value tuple to indicate the three information of a student: name, age, and height, instead of creating an additional class.

var studentInfo = ValueTuple.Create<string, int, uint>("Bob", 28, 175);Console.WriteLine($"Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]");
3. Return multiple values from the method

You can also return multiple values in the function definition instead of the out parameter.

static ValueTuple<string, int, uint> GetStudentInfo(string name){    return new ValueTuple <string, int, uint>("Bob", 28, 175);}
static void RunTest(){ var studentInfo = GetStudentInfo("Bob"); Console.WriteLine($"Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]");}

Differences: The return value can be replaced by the new syntax (,), such as (string, int, uint), without explicitly specifying ValueTuple ):

static (string, int, uint) GetStudentInfo1(string name){    return ("Bob", 28, 175);}
static void RunTest1(){ var studentInfo = GetStudentInfo1("Bob"); Console.WriteLine($"Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]");}

Check whether the type of studentInfo is ValueType.

Differences: The element name can be specified in the return value to facilitate the assignment and access of memory values:

static (string name, int age, uint height) GetStudentInfo1(string name){    return ("Bob", 28, 175);}
static void RunTest1(){ var studentInfo = GetStudentInfo1("Bob"); Console.WriteLine($"Student Information: Name [{studentInfo.name}], Age [{studentInfo.age}], Height [{studentInfo.height}]");}

Easy to remember assignment:

Easy access:

4. multi-value transfer for Single-parameter Methods

When the function parameter is only of the Object type, you can use the value tuples to transmit multiple values.

static void WriteStudentInfo(Object student){    var studentInfo = (ValueTuple<string, int, uint>)student;    Console.WriteLine($"Student Information: Name [{studentInfo.Item1}], Age [{studentInfo.Item2}], Height [{studentInfo.Item3}]");}
static void RunTest(){ var t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(WriteStudentInfo)); t.Start(new ValueTuple<string, int, uint>("Bob", 28, 175)); while (t.IsAlive) { System.Threading.Thread.Sleep(50); }}
5. Deconstruct ValueTuple

You can use var (x, y) or (var x, var y) to parse the value tuples to construct local variables. You can also use the symbol "_" to ignore unnecessary elements.

static (string name, int age, uint height) GetStudentInfo1(string name){    return ("Bob", 28, 175);}static void RunTest1(){    var (name, age, height) = GetStudentInfo1("Bob");    Console.WriteLine($"Student Information: Name [{name}], Age [{age}], Height [{height}]");    (var name1, var age1, var height1) = GetStudentInfo1("Bob");    Console.WriteLine($"Student Information: Name [{name1}], Age [{age1}], Height [{height1}]");    var (_, age2, _) = GetStudentInfo1("Bob");    Console.WriteLine($"Student Information: Age [{age2}]");}

 

As described above, ValueTuple makes C # easier to use. Compared with Tuple, the main advantages are as follows:

  • ValueTuple supports the new syntax "(,)" for returning function values to make the code simpler;
  • You can name the element for ease of use and memory. However, although it is named, in fact, value tuple does not define attributes or fields with such names. The real name is still ItemX, all element names are used only for design and compilation, not for Runtime (so pay attention to serialization and deserialization of this type );
  • You can use the deconstruct method to more easily use elements of some or all tuples;
  • The value tuples are value type, which is more efficient than the reference type tuples and have a comparison method. They can be used to compare the equality of values. For details, see https://msdn.microsoft.com/en-us/library/system.valuetuple.

 

[Original article, reposted, please indicate the source, only for study and research purposes. If there is any error, please leave a message. If you think it is good, please recommend it. Thank you for your support]

[Original: http://www.cnblogs.com/lavender000/p/6916157.html,]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.