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#?
- Dealing with existing structures on disk.
- Advanced COM or Platform Invoke scenarios that involve structures with pointers in them.
- Performance-critical code.
- Interfacing with Operating system.
- Accessing a memory mapped device.
Properties of Unsafe code:
- Methods, types, and code blocks can be defined as unsafe.
- In some cases, unsafe code may increase an application's performance by removing array bounds checks.
- Unsafe code is required when you call native functions that require pointers.
- Using unsafe code introduces security and stability risks.
- 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,
-
-
- class UnsafeDemo
- {
-
- unsafe static void SquarePtr(int* p)
- {
- *p *= *p;
- }
- unsafe static void Main(string[] args)
- {
- int i = 5;
-
- SquarePtr(&i);
- Console.WriteLine(i);
- Console.ReadKey();
- }
- }
-
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.
Execute the program
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.