Topic : Pointers In C# Programming Language: |Unsafe Code|

What is Pointer?

Pointers are a Special type of variables, which can store the Memory address of another variable. They contain a memory address, Not the value of the variable. C# pointer is important in Programming. some C# tasks are performed more easily with the pointer. The concept of the pointers can be well understood from the following example.

Suppose, we Request someone to take a parcel to the house of a person, named Omar. Here the point of reference is a name. However, if we specifically tell him the number of house and the street Number. then this is a reference to the address.



Pointer

Unsafe Code:

To Move on Pointers, We must know about safe and Unsafe code. and to know about safe and unsafe we need to understand about Manage and Unmanaged code.



  • Managed Code:

    Managed code is the code that executes Under the Supervision of CLR. The CLR is Responsible for Various Housekeeping tasks, like:
    » Managing Memory for the Objects:
    » Performing Type Verification:
    » Doing Garbage Collection:



  • Unmanaged Code:

    Unmanaged Code is the code that executes outside the context of the CLR. The Best Example is Our Traditional Win32 DLLS like Kernel32.dll and user32.dll. In Unmanaged Code a Programmer is Responsible for:
    » Calling the Memory Allocation Function:
    » Making sure that the casting is done right:
    » Making sure that the Memory is released when the work is done:



Now let's discuss what is Unsafe code. Unsafe is a C# Programming Language keyword to denote a Section of Code that is Not Managed by The Common Language Runtime (CLR) of the .NET Framework, or Unmanaged Code. Unsafe is used in the Declaration of the type or member or to specify a Block code. When used to Specify a Method, the context of the Entire Method is Unsafe.



To Maintain type safety and Security, C# Does not Support Pointers by Default. However, using the Unsafe Keyword, we can Define an Unsafe Context in Which pointers can be used.



Note:

Before Getting Start with unsafe code, we need to set our compiler to compile an Unsafe Code. By Default Compiler Will Not compile an Unsafe code:

  • In Order to Set Compiler Option in The Visual Studio to Compile an Unsafe code, Follow these Steps:
    » Open The Project's Properties Page
    » Click the Build Property Page.
    » Select the Allow Unsafe Code Check box:

Set compiler to execute an Unsafe code:

Using The Unsafe Modifier:

In order to use the Pointer in C#, We Need to declare our Methods as Unsafe using the Unsafe Keyword: The Basic Example is:


using System;
namespace Pointers
{
   class Program
   {
      static unsafe void Main(string[] args)
      {
           //Body
      }
   }
}


Instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe. The example is:


using System;
namespace Pointers
{
   class Program
   {
      public static void Main()
      {
         unsafe
         {
            //Body:
         }
      }
   }
}


As we Know that, when we declare any variable having any type, the variable reserve some space in different location of computer Memory. and each single location of computer Memory have its own unique Address, which could be accessed using Ampersand ( & ) Operator which denotes an address in Memory. Consider the following Example, which will print the address of the variable defined.



/*Example: Pointers in C#: InfoBrother:*/

using System;

namespace Pointers
{
    class Program
    {
        static void Main(string[] args)
        {
            unsafe   //Unsafe Code:
            {
                int x;
                int* y = &x; //Y point to the Address of X:
                Console.WriteLine("The Address of Variable x is: " + (int)y);

                int** z = &y;  //Pointer to Pointer.
                Console.WriteLine("The Address of Variable y is: " + (int)z);
                Console.ReadKey();    
                           
            }
        }
    }
}


Pointer Declaration:

In C#, When we define a Pointer variable we do so by Preceding its Name with an Asterisk (*). We also give Our Pointer a Date type, which in this case refers to the type of Data stored at the Address we will be storing in Our Pointer. For Example:



 /*Type * Variable-Name;*/

int* Ptr;      //pointer to integer:
int *ptr;      //pointer to integer:
float * fptr;  //pointer to float;
char* cptr;    //pointer to char;  



When We Declare an Pointer, We have several Option When typing the Asterisk (*). White space surrounding it does not matter, so each of the above statements declare an Pointer.



Pointer Initialization:

We declare the point using above syntax, but the pointer "ptr" has no value yet. that is we haven't stored any address int it. so we need to store the address of some variable in it as shown in this example:


 int x;    //declare variable;
 int * y;  //declare an Pointer to Integer:
 y = &x;   //Initialize pointer with the address of x;

 //in short:
 int a;   //declare variable;
 int* b = &a; //declare pointer and initialize it;


In C#, Multiplication ( * ) and the Pointer ( * ) symbol are the same. this fact sometimes confuses Newcomers to the C# Language. These Operators have No Relationship to each other. Keep in Mind that both Ampersand ( & ) and Asterisk ( * ) have a Higher Precedence that any of the Arithmetic Operators except the Unary minus, with which they have equal precedence.



Example:

Let's have an example to Understand the concept of Pointers, in this example, we will declare two variables and assign the value to them. then using pointers we will try to change the value of these variables.


/*Example: Pointers in C#: InfoBrother:*/

using System;

namespace Pointers
{
    class Program
    {
        static void Main(string[] args)
        {
            unsafe   //Unsafe Code:
            {
                int x = 10, y = 20; //variables:
                int* ptr;   //pointer to integer:
                Console.WriteLine("Before x = {0} and y = {1}", x, y);

                ptr = &x;  //Prt point to the address of X;
                *ptr = 5;  //replace the value of x by 5:

                ptr = &y;  //Prt point to the address of y;
                *ptr = 15;  //replace the value of y by 15:

                Console.WriteLine("After x = {0} and y = {1}", x, y);

                Console.ReadKey();

            }
        }
    }
}

In The Above Example, Did you Notice how the values of x and y have changed indirectly. First we have assigned the address of variables to pointer using Address Operator, (&) then using these pointers we changed the value of x and y.



Passing Pointers as Parameters to Methods:

We can pass a Pinter variable to a Method as parameter. Pointer allow us to pass the address of a local variable into a Method, which can then modify the local variable. Let's have an example to know how exactly we can pass the pointer to method as parameter. in this example we will create an method to swap the value store in the variables.


/*Example: Pointers in C#: InfoBrother:*/

using System;

namespace Pointers
{
    class TestPointer
    {
        //swap method:
        public unsafe void swap(int* p, int* q)
        {
            int temp = *p;
            *p = *q;
            *q = temp;
        }

        //main method:
        public unsafe static void Main()
        {
            TestPointer p = new TestPointer();
            int x = 10;
            int y = 20;
            int* var1 = &x;
            int* var2 = &y;

            Console.WriteLine("Before Swap: X:{0}, Y: {1}", x, y);
            p.swap(var1, var2);

            Console.WriteLine("After Swap: X:{0}, Y: {1}", x, y);
            Console.ReadKey();
        }
    }
}


Unsafe code can create issues with stability and security, due to its inherent complex syntax and potential for memory related errors, such as stack overflow, accessing and overwriting system memory. Extra developer care is paramount for averting potential errors or security risks.

















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement