Team LiB
Previous Section Next Section

References and Pointers

Reference variables are the user-defined classes and arrays you have created. References are the default description of what was a pointer in C or C++, and for that matter, is the same as a reference was in C++: a const pointer to memory. One big difference, however, is that, unless you use the fixed keyword, it is possible for the value of a reference to be changed by the GC as it optimizes the use of memory and moves allocations around.

Because a C# reference location might change, you cannot do pointer arithmetic on a reference. To use pointers, you must mark the code as unsafe. Then you declare a pointer type using the following syntax:

MyClass* pMyClass = new MyClass();

This will return a pointer to an instance of MyClass. With this pointer, you can do all the tricks that you could do with C pointers.

Although you can use C-style pointers, it is highly recommended that you use references in lieu of pointers, because they are inherently much safer. For instance, you can use the ++ and −− operators to walk through a pointer to an array. Each time you encounter the ++ or −− operator, you will increment the pointer by the size of the type associated with the pointer. So, if you were using a char*, you would increment the pointer by 2 bytes each time you ran the statement with ++.

The following example demonstrates the use of references and pointers.

Code Example: References and Pointers
Start example

using System;
using System.Runtime.InteropServices;

namespace Client.Chapter_7___Memory_Management
{
      class ReferencesandPointers
      {
            static void Main(string[] args)
            {
                  UsePointers();
            }
           //Creates an unsafe block, which allows for the use of C-style pointers
            static unsafe public void UsePointers()
            {
                  char * pMyArray = (char*)Marshal.AllocCoTaskMem(6);

                  while (*pMyArray != '\0')
                  {
                        Console.WriteLine(*pMyArray);
                        pMyArray++;
                  }

                  Marshal.FreeCoTaskMem((IntPtr)pMyArray);
            }
      }
}
End example

Team LiB
Previous Section Next Section