Monday 10 November 2014

Tuples in C# 4.0

Tuples in C#

One of my favorite features in .NET 4 is the addition of the Tuple.  Tuples allow you to easily capture related values without having to go through the trouble of creating a new class.  It's a much more flexible concept than the KeyValuePair class because they can hold up to 8 values. 

Tuple is a borrowed concept from F# that's been wedged into C# using the power of generics (and the copying and pasting of a class about 8 times). 

Here's an example of the usage

   1: public void Tuple()
   2:          {
   3:              var tup = new System.Tuple<int, string, DateTime>(1, "Brian", DateTime.Now);
   4:              Debug.Write(tup.Item1 + tup.Item2 + tup.Item3);
   5:          }


Here's the class I used above (The version that holds 3 generic values)


   1:  namespace System
   2:  {
   3:      [Serializable]
   4:      public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
   5:      {
   6:          public Tuple(T1 item1, T2 item2, T3 item3);
   7:   
   8:          public T1 Item1 { get; }
   9:       
  10:          public T2 Item2 { get; }
  11:       
  12:          public T3 Item3 { get; }
  13:   
  14:          public override bool Equals(object obj);
  15:          
  16:          public override int GetHashCode();
  17:        
  18:          public override string ToString();
  19:      }
  20:  }

Interesting to note that, yes there are 8 different versions of the class to support Tuples that hold up to 8 values.

For more details check - http://msdn.microsoft.com/en-us/library/system.tuple.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

No comments:

Post a Comment