Detailed explanation of tuple instance of new feature of C syntax


1. Tuples (Tuple)

Tuples (Tuple) have existed since 4.0, but tuples also have some disadvantages, such as:

  1. Tuple affects the readability of the code because its attribute names are: Item1, Item2.

  2. Tuple is not lightweight enough, because it is a reference type (Class), and it is a bit unnecessary to use one type for one variable.

The source code is as follows:

 //  Summary :
  //    Provides static methods for creating tuple objects. To browse for this type of .NET Framework  Source code, see  Reference Source .
  public static class Tuple
  {
    //  Return results :
    //   1 Tuples whose values  (item1) .
    public static Tuple<T1> Create<T1>(T1 item1);
    //  Return results :
    //   1 A  2  Tuple whose value  (item1,  , item2) .
    public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2);
  }

Provides static methods for creating tuple objects

Note: The Tuple mentioned above is not lightweight enough, which is in a sense or a hypothesis, that is, it assumes that there are many allocation operations.

The tuple (ValueTuple) in C # 7 addresses both of these drawbacks:

  1. ValueTuple supports semantic field naming, and can customize the name for every attribute name, such as (int first, int second) tuple = (1, 2).

  2. ValueTuple is a value type (Struct).

Note: If the vs report does not have a predefined type ValueTuple < … > You need to use the nuget command to import: Install-Package System. ValueTuple

The source code is as follows (ValueTuple < … > Internal principle):

public struct ValueTuple<T1, T2> : IEquatable<ValueTuple<T1, T2>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2>>, ITupleInternal
  {
    public T1 Item1;
    public T2 Item2;
    int ITupleInternal.Size
    {
      get
      {
        return 2;
      }
    }
    public ValueTuple(T1 item1, T2 item2)
    {
      this.Item1 = item1;
      this.Item2 = item2;
    }
     }

Summary: The appearance of tuples simplifies object-oriented to a certain extent, and some unnecessary or rarely used objects can be returned directly by tuples instead of being returned by types