Pointers And Unsafe Code

C# does not allow pointer arithmetic by default to maintain security and safety. However we can use the pointer in C# using keyword ‘unsafe’. Unsafe does not necessarily dangerous but it’s just a code which cannot be verified by .Net Common Language Runtime (CLR). So this is clearly means it’s totally your responsibility to ensure that your code does not introduce security threat or pointer error to your application.

Why do you want unsafe code and pointers in C#?

  1. Dealing with existing structures on disk.
  2. Advanced COM or Platform Invoke scenarios that involve structures with pointers in them.
  3. Performance-critical code.
  4. Interfacing with Operating system.
  5. Accessing a memory mapped device.

Properties of Unsafe code:

  1. Methods, types, and code blocks can be defined as unsafe.
  2. In some cases, unsafe code may increase an application's performance by removing array bounds checks.
  3. Unsafe code is required when you call native functions that require pointers.
  4. Using unsafe code introduces security and stability risks.
  5. In order for C# to compile unsafe code, the application must be compiled with ‘/unsafe.’

You can use the ‘unsafe’ modifier in the declaration of a type or a member. The entire textual extent of the type or member is therefore considered an unsafe context. For example, the following is a method declared with the ‘unsafe’ modifier,

  1. // compile with: /unsafe  
  2.   
  3. class UnsafeDemo  
  4. {  
  5. // Unsafe method: takes pointer to int:  
  6. unsafe static void SquarePtr(int* p)  
  7. {  
  8. *p *= *p;  
  9. }  
  10. unsafe static void Main(string[] args)  
  11. {  
  12. int i = 5;  
  13. // Unsafe method: uses address-of operator (&):  
  14. SquarePtr(&i);  
  15. Console.WriteLine(i);  
  16. Console.ReadKey();  
  17. }  
  18. }   
  19. // Output: 25  
How to compile unsafe code:

To set this compiler option in the Visual Studio development environment.

Open the project's ‘Properties’ page.

Click the ‘Build’ property page.

Select the ‘Allow Unsafe Code’ check box.

build

Execute the program

Execute

Summary

Although unsafe code is rarely used I think C# developers should know this exists and how we can use it. Only beware of the security risk which could kill your hard work.


Similar Articles