29.3 Introducing pointers


There are three types in C#: value type, reference type, and the pointer type. Value types and reference types have been thoroughly covered in Chapter 9. Pointer types are only used in unsafe codes.

You will realize that pointer types are, in fact, very similar to reference types with two main differences. Like a pointer type, a reference type does not store the actual object or the values stored in the fields of an object, rather it stores an address to the actual object on the heap.

However, with a reference type you are unable to retrieve the actual address of the object it is referencing. C# shields you from all these low-level issues. You can retrieve the address of an object pointed to by a pointer type though. The second difference is that a reference type is tracked by the garbage collector, but a pointer type is not. The garbage collector is totally ignorant of the existence of pointers, and the data they point to.

There are other differences between these two types:

  • pointer types do not inherit from System.Object “ you cannot cast a pointer type to System.Object

  • boxing and unboxing do not work on pointers.

Pointer types are not used frequently because, most of the time, reference types are good enough (if you do not need to know the address of an object a reference type variable is referring to). When you need to change the value of any field of the object, all you have to do is to assign the new value via the reference type variable. The address is automatically resolved for you “ you don't need, or want, to know whether the object is stored at 0x9999 or 0x8888 . When the .NET CLR needs to shift the object to another address in order to optimize memory use, it performs the shift and updates the reference type variable of the new address it should refer to. All this is totally transparent to the developer.

Nevertheless, when there are special circumstances (the same circumstances in which you would want to write unsafe codes) whereby you need to get the actual address of an object in order to manipulate its contents manually, you can do it via pointer types.

Like a reference variable, a pointer variable is one that stores a memory address. The difference is that you can retrieve the address of the object a pointer is referencing (or pointing to, in this case) and do what you want with it.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net