13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

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

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

<strong>C#</strong> LANGUAGE SPECIFICATIONclass Test{static void Main() {Digit a = (Digit) 5;Digit b = (Digit) 3;Digit plus = a + b;Digit minus = a - b;bool equals = (a == b);Console.WriteLine("{0} + {1} = {2}", a, b, plus);Console.WriteLine("{0} - {1} = {2}", a, b, minus);Console.WriteLine("{0} == {1} = {2}", a, b, equals);}}The Digit type defines the following operators:• An implicit conversion operator from Digit to byte.• An explicit conversion operator from byte to Digit.• An addition operator that adds two Digit values and returns a Digit value.• A subtraction operator that subtracts one Digit value from another, and returns a Digit value.• The equality (==) and inequality (!=) operators, which compare two Digit values.8.7.7 IndexersAn indexer is a member that enables an object to be indexed in the same way as an array. Whereasproperties enable field-like access, indexers enable array-like access.As an example, consider the Stack class presented earlier. The designer of this class might want to exposearray-like access so that it is possible to inspect or alter the items on the stack without performingunnecessary Push and Pop operations. That is, class Stack is implemented as a linked list, but it alsoprovides the convenience of array access.Indexer declarations are similar to property declarations, with the main differences being that indexers arenameless (the “name” used in the declaration is this, since this is being indexed) and that indexersinclude indexing parameters. The indexing parameters are provided between square brackets. The exampleusing System;public class Stack{private Node GetNode(int index) {Node temp = first;while (index > 0) {temp = temp.Next;index--;}return temp;}public object this[int index] {get {if (!ValidIndex(index))throw new Exception("Index out of range.");elsereturn GetNode(index).Value;}set {if (!ValidIndex(index))throw new Exception("Index out of range.");elseGetNode(index).Value = value;}}…}38

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

Saved successfully!

Ooh no, something went wrong!