miercuri, 2 decembrie 2009

[.NET] [4.0] Generic tuples classes

-> Microsoft .NET Framework introduces a new type called System.Tuple

Tuples are a group of properties that provide a means for you to easily group pieces of data together without having to write your own classes.
Or:
Tuple is a fixed-size collection of heterogeneously typed data.

-> You'll find tuples in languages such as Python and F#


Sample:
class Tuple
{
T1 Item1 { get; }
T2 Item2 { get; }
}

Tuple person = new Tuple ( "George", 28);
Console.WriteLine(person.Item1 + " " + person.Item2);

var _tuplePerson = Tuple.Create("George", 28);

-> This class allows you to group two different pieces of data of any type.

-> Tuples in .NET are considered immutable.
-> Like an array, a tuple has a fixed size that can't be changed once it has been created. Unlike an array, each element in a tuple may be a different type, and a tuple is able to guarantee strong typing for each element.
-> KeyValuePair is a sample of Tuple
-> All tuples are reference types (this may hit the performance).
-> Can have till 8 generic parameters
-> The last element of an eight-element tuple would be called "Rest" and it is required to be a tuple.
Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8));

-> Both Tuple and Array now implement these interfaces explicitly: IStructualEquatable and IStructuralComparable

One problem with tuples is your code becomes less descriptive, because tuples employ non-descript property names such a person.Item1 and person.Item2.

Niciun comentariu:

Trimiteți un comentariu