15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

146 ❘ ChaPTer 6 ArrAys And tuples<br />

}<br />

}<br />

}<br />

yield break;<br />

yield return cross;<br />

code snippet YieldDemo/GameMoves.cs<br />

From the client program, you can use the class GameMoves as follows. The first move is set by setting<br />

enumerator to the enumerator type returned by game.Cross(). In a while loop, enumerator.MoveNext()<br />

is called. The first time this is invoked, the Cross() method is called, which returns the other enumerator<br />

with a yield statement. The returned value can be accessed with the Current property <strong>and</strong> is set to the<br />

enumerator variable for the next loop:<br />

var game = new GameMoves();<br />

IEnumerator enumerator = game.Cross();<br />

while (enumerator.MoveNext())<br />

{<br />

enumerator = enumerator.Current as IEnumerator;<br />

}<br />

The outcome of this program shows alternating moves until the last move:<br />

Cross, move 0<br />

Circle, move 1<br />

Cross, move 2<br />

Circle, move 3<br />

Cross, move 4<br />

Circle, move 5<br />

Cross, move 6<br />

Circle, move 7<br />

Cross, move 8<br />

code snippet YieldDemo/Program.cs<br />

TuPles<br />

Arrays combine objects of the same type; tuples can combine objects of different types. Tuples have the<br />

origin in functional programming languages such as F# where they are used often. With .<strong>NET</strong> 4, tuples are<br />

available with the .<strong>NET</strong> Framework for all .<strong>NET</strong> languages.<br />

.<strong>NET</strong> 4 defines eight generic Tuple classes <strong>and</strong> one static Tuple class that act as a factory of tuples. The<br />

different generic Tuple classes are here for supporting a different number of elements; e.g., Tuple<br />

contains one element, Tuple contains two elements, <strong>and</strong> so on.<br />

The method Divide() demonstrates returning a tuple with two members — Tuple. The<br />

parameters of the generic class define the types of the members, which are both integers. The tuple is created<br />

with the static Create() method of the static Tuple class. Again, the generic parameters of the Create()<br />

method define the type of tuple that is instantiated. The newly created tuple is initialized with the result<br />

<strong>and</strong> reminder variables to return the result of the division:<br />

public static Tuple Divide(int dividend, int divisor)<br />

{<br />

int result = dividend / divisor;<br />

int reminder = dividend % divisor;<br />

}<br />

return Tuple.Create(result, reminder);<br />

code snippet TuplesSample/Program.cs<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!