Abstract
In .NET, unsafe code really means potentially unsafe code, that is code or memory that exists outside the normal boundary. This article digs into the details of legacy C programming pointer implementation in the .NET Framework. We however will seldom need to use pointer types. Unsafe code can access unmanaged memory resources, that are outside the realm of the CLR. You can access unmanaged memory with raw pointers, that are only available to unsafe code. Finally, the use of pointers is very risky and prone to abuse because we need to manually manage the memory-related subtle tasks.
Unsafe Coding
In unsafe coding, developers can access raw legacy pointers in the .NET Framework environment. You can use pointer operators, such as & and *. As in the semantic of perfect programming practices, pointers should be avoided to make your code safer because they interrupt the normal operations of the Garbage Collector and they point to a fixed location in unmanaged memory whereas reference types point to a movable location is managed memory. But the question arises if pointers are so dangerous then why we are practicing unsafe coding? Why does the .NET Framework allow pointers? Use of unsafe coding or pointers is however sometimes necessary, for example porting C/C++ algorithms that heavily rely on pointers is very beneficial. There are certain circumstances in which unsafe is recommended.
- Calling an unmanaged function that requires a function pointer as a parameter.
- Unmanaged pointers no doubt improve performance and efficiency.
- Pointers might be easier and more convenient when working with binary and memory-resident data structures.
Safe Coding
Improper pointer management causes many common problems, including memory leaks, accessing invalid memory, and deleting bad pointers. Safe coding is limited to accessing the managed heap. The managed heap is managed by the Garbage Collector, which is an essential component of the common language runtime. Code restricted to the managed heap is intrinsically safer than code that accesses unmanaged memory. The CLR automatically releases unused objects, conducts type verification, and performs other checks on managed memory. So, all this is not done automatically for unmanaged code, instead, the developer is responsible for these tasks. With managed coding, the developer can only focus on core application development instead of various administrative tasks such as memory management.
Note: Code in an unmanaged section is considered unsafe and not accessible to the CLR. Therefore, no code verification or stack tracing is done on the unmanaged code.
Pointers Implementation
Managed applications that include unsafe code must be compiled with the unsafe option. The C# compiler option is simply "/unsafe". In the Visual Studio 2010 IDE, this option is found under solution properties, in the build tab. You just need to check this option in order to compile the unsafe code that is leveraged with pointers.
Note: Unsafe coding and pointer implementation require some background of C++ pointer manipulation.

- class Program
- {
- static void Main(string[] args)
- {
- //// pointers won't work here
- unsafe
- {
- // pointer manipulation (&, *)
- }
- }
- }
- public unsafe class test
- {
- unsafe int x = 10;
- unsafe void myMethod(int* x)
- {
- }
- }
- using System;
- namespace unsafePro
- {
- class Program
- {
- static void Main(string[] args)
- {
- unsafe
- {
- double x = 10;
- sqrt(&x);
- }
- Console.ReadKey();
- }
- unsafe static void sqrt(double* i)
- {
- Console.WriteLine("Square Root is={0}",Math.Sqrt(*i));
- }
- }
- }
- static void Main(string[] args)
- {
- unsafe
- {
- double x = 10;
- sqrt(&x);
- }
- int y = 5;
- sqrt(&y); //compile time error
- }
- unsafe static void Main(string[] args)
- {
- double x = 10;
- sqrt(&x);
- }
- unmanagedtype* identifier;
- int* x,y;
- int *x, *y; // Wrong Syntax error
- namespace unsafePro
- {
- public struct xyz
- {
- public int x;
- public int y;
- }
- class Program
- {
- static void Main(string[] args)
- {
- unsafe
- {
- xyz obj = new xyz();
- xyz* aa = &obj;
- aa->x = 200;
- aa->y = 400;
- Console.WriteLine("X is={0}", aa->x);
- Console.WriteLine("Y is={0}", aa->y);
- }
- Console.ReadKey();
- }
- }
- }
- static void Main(string[] args)
- {
- unsafe
- {
- Console.WriteLine("Int size is={0}", sizeof(int));
- Console.WriteLine("Int16 size is={0}", sizeof(Int16));
- Console.WriteLine("Int32 size is={0}", sizeof(Int32));
- Console.WriteLine("Int64 size is={0}", sizeof(Int64));
- }
- }

- unsafe static string data()
- {
- char* buffer = stackalloc char[5];
- for (int i = 0; i < 5; i++)
- {
- buffer[i] = 'a';
- }
- return new string(buffer);
- }

Casper BarchagerPosted Dec 6, 2014, 3:16 PM
In what scenario would you use pointers in C#? - Your sizeof example works perfectly fine without the unsafe keyword.
Max AlbishPosted Nov 7, 2014, 5:06 PM
did stackalloc equivalent declare a array of pointer or what ?
Sam HobbsPosted Nov 5, 2014, 12:59 PM
Pointers are safer in C and C++ because the C and C++ compilers support them better. Most C++ programmers however avoid pointers. The designer of the C++ language, Bjarne Stroustrup, dislikes pointers so much that he designed "references" for C++. C++ "references" are not the same thing as CLI (.Net) reference types. C++ "references" are pointers with an improved and safer syntax. The .Net Framework does not support C++ references because they can only be used by the C++ compiler but they are safer than pointers.