Writing Unsafe Code in C#
When you develop your application in C#, your code will be well managed and you need not write explicit coding to perform garbage collection or any other memory management. Memory Management and Garbage Collection are handled by CLR (Common Language Runtime).
However there are situations when you want control over certain blocks of memory. For example, to interface your application with an operating system or to use winAPI functions in your code. In such cases, using pointers will be of more help. However using pointers will disturb memory content directly and it is not recommended by CLR. But still you can accomplish it by writing unsafe code in C#.
How to Write Unsafe Code?
If you are
using pointers in your code, you have to mark that block of code as unsafe
using the keyword unsafe. You can even mark a class or method
as unsafe. Heres an example for code using pointers:
Though this code looks fine in its functionality, it uses pointers. Hence either the code block or method containing the code or its associated class has to be marked as unsafe. Since that is not done, you will get the following error during compilation: CS0214: Pointers may only be used in an unsafe context
You can eliminate
this error by modifying the code as shown below:
You can also
mark the specific block of code as unsafe, as shown below:
Using Fixed Pointers:
Garbage Collector can relocate objects in the heap to gather continuous block of free space. In those cases, pointers pointing to the objects memory location will be made to point to the modified location. This works fine for the managed code which you write. But if the object is part of unsafe code, the pointer will not be corrected to point to the modified location. This will lead to dangling references. To avoid such problems, you have to ensure that garbage collector does not move objects referred by pointers of unsafe code. This can be done by making those pointers as fixed. Whenever you access address of an object using a pointer, use the keyword fixed. Modify the following line of code from the above mentioned unsafe block to use the keyword fixed:
int* addressValue = &testData
version of this line of code will be:
Though pointers are advantageous, it is dangerous in terms of memory management. Hence ensure proper usage of pointers by writing unsafe code and by marking the associated pointers as fixed.