Tuples

Tuples are set of generic classes for holding a set of differently typed elements. Where each has read-only properties called Item1, Item2.

Creating Tuples

1. Using Constructor

var t = new Tuple (123, "Hello");

2. Static Helper method

Tuple t = Tuple.Create(123, "Hello");

3. Using Implicit Type

var t = Tuple.Create(123, "Hello");

Accessing the Tuple Properties

Console.WriteLine (t1.Item1 * 2);         // 246
Console.WriteLine (t1.Item2.ToUpper());   // HELLO

// The alternative sacrafices static type safety and causes boxing with value types:

object[] items = { 123, "Hello" };
Console.WriteLine ( ((int)    items[0]) * 2       );   // 246
Console.WriteLine ( ((string) items[1]).ToUpper() );   // HELLO

Tuples are convenient in returning more than one value from a method or creating collections of value pairs. Alternative to tuples is to use an object array but with limitations such as boxing and unboxing.

Comparing Tuples

Tuples are classes so reference types. The equality operator returns false where as the Equals method is overridden to compare each individual element.

var t1 = Tuple.Create (123, "Hello");
var t2 = Tuple.Create (123, "Hello");

Console.WriteLine (t1 == t2);           // False
Console.WriteLine (t1.Equals (t2));     // True

Guid Struct

The Guid struct represents a globally unique identifier: a 16-byte value when generated is almost unique in every way.

To instantiate an existing value, you use the constructors.

public Guid (byte[] b); //Accepts a 16-byte array
public Guid (string g); //Accepts a formatted string
//generate new unique Guid
Guid g = Guid.NewGuid ();
g.ToString().Dump ("Guid.NewGuid.ToString()");

Guid g1 = new Guid ("{0d57629c-7d6e-4847-97cb-9e2fc25083fe}");
Guid g2 = new Guid ("0d57629c7d6e484797cb9e2fc25083fe");
Console.WriteLine (g1 == g2);  // True

byte[] bytes = g.ToByteArray();
Guid g3 = new Guid (bytes);
g3.Dump();

Guid.Empty.Dump ("Guid.Empty");
default(Guid).Dump ("default(Guid)");
Guid.Empty.ToByteArray().Dump ("Guid.Empty - bytes");

Leave a Reply

Your email address will not be published. Required fields are marked *