Game Development Reference
In-Depth Information
The compiler will not even permit a variable address with pointers unless the memory for the vari-
able is pinned within a fixed statement.
Disabling Arithmetic Overflow Checking
Another keyword that is relevant to unsafe pointer usage is the unchecked keyword.
Specifying unchecked allows you to suppress overflow-checking for integral-type
arithmetic operations and conversions. If an expression produces a value that is
outside the range of the destination data type, then the result is truncated. For
example, trying to evaluate the following code will set myNumber equal to -1014837864 .
int myNumber = (int)3181555928472; // Evaluates to -1014837864
The unchecked keyword causes the compiler to ignore the fact that the value is too
large for the integer data type. Had the unchecked keyword not been specified, then
the compiler would have thrown compile time errors because the sizes are known
and the values are constant. Otherwise, an OverflowException would have been
thrown at runtime.
You can also use the unchecked keyword as an operator, as in the following example.
public int AddNumbers(int left, int right)
return unchecked(left + right);
Running code, especially numeric-intensive calculations, within an unchecked
block can boost the overall speed and performance of the executing code. You have
to be careful to watch your data type sizes though.
Allocating High Performance Memory
You can use the keyword stackalloc to allocate a block of memory on the stack. This
only works with value types, and the memory is not subject to garbage collection,
so it does not have to be pinned. The lifetime of the memory block is limited
to the scope of the executing method; stackalloc is only valid in local variable
Search Nedrilad ::

Custom Search