13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>C#</strong> LANGUAGE SPECIFICATION}public void Push(object o) {first = new Node(o, first);}class Node{public Node Next;public object Value;public Node(object value): this(value, null) {}public Node(object value, Node next) {Next = next;Value = value;}}shows a Stack class implemented as a linked list of Node instances. Node instances are created in the Pushmethod and are garbage collected when no longer needed. A Node instance becomes eligible for garbagecollection when it is no longer possible for any code to access it. For instance, when an item is removedfrom the Stack, the associated Node instance becomes eligible for garbage collection.The exampleclass Test{static void Main() {Stack s = new Stack();for (int i = 0; i < 10; i++)s.Push(i);s = null;}}shows code that uses the Stack class. A Stack is created and initialized with 10 elements, and thenassigned the value null. Once the variable s is assigned null, the Stack and the associated 10 Nodeinstances become eligible for garbage collection. The garbage collector is permitted to clean up immediately,but is not required to do so.The garbage collector underlying <strong>C#</strong> may work by moving objects around in memory, but this motion isinvisible to most <strong>C#</strong> developers. For developers who are generally content with automatic memorymanagement but sometimes need fine-grained control or that extra bit of performance, <strong>C#</strong> provides theability to write “unsafe” code. Such code can deal directly with pointer types and object addresses, however,<strong>C#</strong> requires the programmer to fix objects to temporarily prevent the garbage collector from moving them.This “unsafe” code feature is in fact a “safe” feature from the perspective of both developers and users.Unsafe code must be clearly marked in the code with the modifier unsafe, so developers can't possibly useunsafe language features accidentally, and the compiler and the execution engine work together to ensurethat unsafe code cannot masquerade as safe code. These restrictions limit the use of unsafe code to situationsin which the code is trusted.The exampleusing System;class Test{static void WriteLocations(byte[] arr) {unsafe {fixed (byte* pArray = arr) {byte* pElem = pArray;for (int i = 0; i < arr.Length; i++) {byte value = *pElem;Console.WriteLine("arr[{0}] at 0x{1:X} is {2}",i, (uint)pElem, value);pElem++;}}}}26

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

Saved successfully!

Ooh no, something went wrong!