Pointers and UnSafe Code Introduction in C#

Pointers in any programming language point to the memory address of a variable. It directly points to value stored in a memory address which assigned to another variable (this variable is not a pointer). Pointers are not typed safety and do not support by CLR for security reasons. 

Even though pointers are not compatible by CLR, we can still use them in C# by using unsafe keyword. Before going to discuss more about Pointers and unsafe code first, we have to know why and when we need to use pointers. We can use pointers when performance is a primary concern because by using pointers we can avoid unnecessary run-time type safety checks. Pointers can also be used to build data structures like Stack, Queue, List, etc. 

CLR cannot execute pointers, so we have to define pointers in the unsafe environment using unsafe keyword because pointers are not derived from Object class in C#. We cannot do boxing and unboxing the pointers because of it is unsafe. And also pointers cannot point to reference type of variables for example pointers can not point to struct contains reference type. An enum type, user, defined struct type which contains unmanaged field type, int, uint, long, ulong, sbyte, byte, short, ushort, char, float, double, decimal, and bool types can be a point to pointer. 

We can declare pointers by using the unsafe keyword in C#. Open Microsoft Visual Studio 2015 => Create a new Console application and name it as CSharpUnsafe. We should inform the compiler that we include unsafe code. To do that right click on solution and select properties. Go to Build and enable “Allow unsafe code” as shown below. 

Add new class Employee to the project and declare the class as unsafe using an unsafe keyword as shown below. 

namespace CSharpUnsafe

{

    internal unsafe class Employee

    {

        private unsafe void GetEmployeeName()

        { 

        } 

        private void GetEmployeeDetails()

        { 

        }

    }

} 

You can declare pointer type by using an asterisk (*) symbol. Declare integer pointers which hold the address of integer variables. 

using System; 

namespace CSharpUnsafe

{

    class Program

    {

        static void Main(string[] args)

        {

            unsafe

            {

                int i1 = 100;

                int* ptr1 = &i1;

                int* ptr2 = ptr1; 

                Console.WriteLine("Value: " + *ptr1);

                Console.WriteLine("Address: " + (int)ptr1);

                Console.WriteLine("Value of ptr2: " + *ptr2);

                Console.WriteLine("Address of ptr2: " + (int)ptr2);

                Console.ReadLine();

            }

        }

    }

} 

Run the application, and it displays the address and value of the int variable through a pointer.