4

Click here to load reader

c# tuple

Embed Size (px)

DESCRIPTION

c# tuple example

Citation preview

Page 1: c# tuple

A Tuple has many items. Each itemcan have any type. The Tuple classprovides a unified syntax for creatingobjects with typed fields. Once created,the fields in the Tuple cannot bemutated. This makes the Tuple similar to a value type.Class

3 itemsPlease note that the Tuple type is a class. Itwill be allocated in a separate location onthe managed heap in memory. Once youcreate the Tuple, you cannot change thevalues of its fields. This makes the Tuplemore like a struct.Struct

Next:In this example, we create a three-item tuple using the specialconstructor syntax.

And:We then read the Item1, Item2, and Item3 properties. We do notmodify them.

Program that uses 3 items in Tuple [C#]

using System;

class Program{ static void Main() {

// Create three-item tuple.Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "cat", true);// Access tuple properties.if (tuple.Item1 == 1){ Console.WriteLine(tuple.Item1);}if (tuple.Item2 == "dog"){ Console.WriteLine(tuple.Item2);}if (tuple.Item3){ Console.WriteLine(tuple.Item3);}

}}

Output

1True

Different types of items. When you create theTuple, you can change the order and types of thefields in any way you want. If you would ratherhave a double, byte, char Tuple, change thedeclaration to Tuple<double, byte, char>.

Notice:You can have value types such as int and reference types such asstring inside the Tuple.

4 itemsContinuing on, the Tuple type can havemore complex items inside it, such asarrays. You can also pass the Tuple type toother methods. In this example, we createa four-item Tuple with two arrays.Array

Then:We initialize those arrays inside the constructor invocation. Nextwe pass the Tuple variable to another method.

Program that uses four-item Tuple [C#]

using System;

class Program{ static void Main() {

// Create four-item tuple; use var implicit type.var tuple = new Tuple<string, string[], int, int[]>("perl",

C# Tuple Examples http://www.dotnetperls.com/tuple

1 of 4 1/12/2013 11:01 AM

Page 2: c# tuple

new string[] { "java", "c#" }, 1, new int[] { 2, 3 });// Pass tuple as argument.M(tuple);

}

static void M(Tuple<string, string[], int, int[]> tuple) {

// Evaluate the tuple's items.Console.WriteLine(tuple.Item1);foreach (string value in tuple.Item2){ Console.WriteLine(value);}Console.WriteLine(tuple.Item3);foreach (int value in tuple.Item4){ Console.WriteLine(value);}

}}

Output

perljavac#123

Var Tuple. Why does the example usethe var keyword? The reason is puresyntactic sugar: it shortens the lines inthe code example. If you were to typeout the entire declaration twice, itwouldn't look as pretty.Var Examples

SextupleA sextuple has six items. To create a sextuple, use the Tupleconstructor. You have to specify each type of the sextuple's items inthe type parameter list. In the sextuple constructor, you then specifythe values that will be stored.

Program that uses sextuple [C#]

using System;

class Program{ static void Main() {

var sextuple = new Tuple<int, int, int, string, string, string>(1, 1, 2, "dot", "net", "perls");Console.WriteLine(sextuple);

}}

Output

(1, 1, 2, dot, net, perls)

In Visual Studio, you can hover over the varkeyword. This will show you that the var"Represents a 6-tuple, or sextuple." VisualStudio will further describe the individual typesof the arguments of the Tuple instance.Visual Studio

Note:The naming of tuples is not important inmany programs. But these terms can beuseful when describing programs in a conciseway.

The main difference between the Tuple typeand a sextuple is that a Tuple can store nearlyany number of items, while a sextuple musthave six. Beyond septuples, we only have n-tuples.

A 2-tuple is called a pair.A 3-tuple is called a triple.A 4-tuple is called a quadruple.A 5-tuple is called a quintuple.A 6-tuple is called a sextuple.A 7-tuple is called a septuple.Larger tuples are called n-tuples.

Tuple.Create

C# Tuple Examples http://www.dotnetperls.com/tuple

2 of 4 1/12/2013 11:01 AM

Page 3: c# tuple

Next, we invoke the Tuple.Createmethod. We use it with three arguments:a string literal, an integer, and a booleanvalue. The result of this method call is atuple of type Tuple<string, int, bool>.

Also, we can use the implicit type var tosimplify the syntax. The rest of the program simply tests the Item1,Item2, and Item3 property accessors. It prints the default stringrepresentation of the Tuple instance.

Program that uses Tuple.Create method [C#]

using System;

class Program{ static void Main() {

// Use Tuple.Create static method.var tuple = Tuple.Create("cat", 2, true);

// Test value of string.string value = tuple.Item1;if (value == "cat"){ Console.WriteLine(true);}

// Test Item2 and Item3.Console.WriteLine(tuple.Item2 == 10);Console.WriteLine(!tuple.Item3);

// Write string representation.Console.WriteLine(tuple);

}}

Output

TrueFalseFalse(cat, 2, True)

What does this Tuple.Create methodreally do? Surely there must be someelaborate algorithm involved in creatinga tuple. The Tuple.Create methodsimply calls the constructor and returns the reference returned by theconstructor.

Tip:There is essentially no functional reason to ever call Tuple.Create.It might have more pleasing syntax.

One implementation of Tuple.Create [.NET 4.0]

public static Tuple<T1> Create<T1>(T1 item1){ return new Tuple<T1>(item1);}

ImplementationThe most important thing to know aboutthe Tuple type is that it is a class, not astruct. It thus will be allocated upon themanaged heap. Each class instance that isallocated adds to the burden of garbage collection.

Note:The properties Item1, Item2, and further do not have setters. Youcannot assign them. The Tuple is immutable once created inmemory.Property

Read-onlyAs noted, you must initialize all the values insidethe Tuple instance to their final values when youcall the Tuple constructor. You cannot change thevalue of a property like Item1 after the constructor has been called.

In this way, the Tuple acts like a struct in that its fields areimmutable. This limitation can lead to more maintainable code thatdoes not rely on field changes through time. It can also reduceperformance.

Error:Property or indexer 'System.Tuple...Item1' cannot be assignedto—it is read-only.

Performance

C# Tuple Examples http://www.dotnetperls.com/tuple

3 of 4 1/12/2013 11:01 AM

Page 4: c# tuple

Some performance tests were run on the Tupleand the KeyValuePair struct. This performancecomparison is only relevant in cases where aTuple of two items is used, as the KeyValuePairalways has two items.

In the performance tests, KeyValuePairwas faster when many instances werecreated, but Tuple was faster when theinstance was passed to many methods as anargument. This is because the Tuple is aclass and the KeyValuePair is a struct.Tuple Versus KeyValuePair

SortHow can you sort a collection of Tupleinstances in an efficient andappropriate way? With the Comparisondelegate, you can sort an array or Listof Tuple instances. It doesn't matterhow many items the Tuple instances contain.Sort Tuple List

SummaryThe Tuple is a typed, immutable andgeneric construct. It is a useful containerfor storing conceptually related data. Asimple class with commented membersand additional methods is more useful forimportant things.

Review:Tuple falls short in the field of information hiding. It excels as auseful short-term container.

C# Tuple Examples http://www.dotnetperls.com/tuple

4 of 4 1/12/2013 11:01 AM