■
Source Code
The CustomConversions project is located under the Chapter 12 subdirectory.
Working with Pointer Types
In Chapter 4, you learned that the .NET platform defines two major categories of data: value types
and reference types. Truth be told, however, there is a third category:
pointer types. To work with
pointer types, we are provided with specific operators and keywords that allow us to bypass the
CLR’s memory management scheme and take matters into our own hands (see Table 12-3).
Table 12-3.
Pointer-Centric C# Operators and Keywords
Operator/Keyword
Meaning in Life
*
This operator is used to create a pointer variable (i.e., a variable that
represents a direct location in memory). As in C(++), this same operator is
used for pointer indirection.
&
This operator is used to obtain the address of a variable in memory.
->
This operator is used to access fields of a type that is represented by a pointer
(the unsafe version of the C# dot operator).
[]
The [] operator (in an unsafe context) allows you to index the slot pointed to
by a pointer variable (recall the interplay between a pointer variable and the
[] operator in C(++)!).
++, --
In an unsafe context, the increment and decrement operators can be applied
to pointer types.
+, -
In an unsafe context, the addition and subtraction operators can be applied
to pointer types.
==, !=, <, >, <=, =>
In an unsafe context, the comparison and equality operators can be applied
to pointer types.
stackalloc
In an unsafe context, the stackalloc keyword can be used to allocate C#
arrays directly on the stack.
fixed
In an unsafe context, the fixed keyword can be used to temporarily fix a
variable so that its address may be found.
Now, before we dig into the details, let me point out the fact that you will
seldom if ever need to
make use of pointer types. Although C# does allow you to drop down to the level of pointer manipu-
lations, understand that the .NET runtime has absolutely no clue of your intentions. Thus, if you
mismanage a pointer, you are the one in charge of dealing with the consequences. Given these
warnings, when exactly would you need to work with pointer types? There are two common
situations:
• You are looking to optimize select parts of your application by directly manipulating mem-
ory outside the management of the CLR.
• You are calling methods of a C-based *.dll or COM server that demand pointer types as
parameters. Even in this case, you can often bypass the use of pointer types in favor of the
System.IntPtr type and members of the System.Runtime.InteropServices.Marshal type.
C H A P T E R 1 2
Do'stlaringiz bilan baham: |