Free mag vol1 | Page 494

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES // Assign value of myInt using pointer indirection. *ptrToMyInt = 123; } // Print some stats. Console.WriteLine("Value of myInt {0}", myInt); Console.WriteLine("Address of myInt {0:X}", (int)&ptrToMyInt); An Unsafe (and Safe) Swap Function Of course, declaring pointers to local variables simply to assign their value (as in the previous example) is never required and not altogether useful. To illustrate a more practical example of unsafe code, assume you want to build a swap function using pointer arithmetic: unsafe public static void UnsafeSwap(int* i, int* j) { int temp = *i; *i = *j; *j = temp; } Very C-like, don’t you think? However, given your work in previously, you should be aware that you could write the following safe version of your swap algorithm using the C# ref keyword: public static void SafeSwap(ref int i, ref int j) { int temp = i; i = j; j = temp; } The functionality of each method is identical, thus reinforcing the point that direct pointer manipulation is not a mandatory task under C#. Here is the calling logic using a safe Main(), with an unsafe context: static void Main(string[] args) { Console.WriteLine("***** Calling method with unsafe code *****"); // Values for swap. int i = 10, j = 20; // Swap values "safely." Console.WriteLine("\n***** Safe swap *****"); Console.WriteLine("Values before safe swap: i = {0}, j = {1}", i, j); SafeSwap(ref i, ref j); Console.WriteLine("Values after safe swap: i = {0}, j = {1}", i, j); // Swap values "unsafely." Console.WriteLine("\n***** Unsafe swap *****"); Console.WriteLine("Values before unsafe swap: i = {0}, j = {1}", i, j); 434