Pointers in C#

In this article we’ll discuss Pointers in C# with the help of example. In C#, you can use pointers but with unsafe keyword only. You can also check our related article of pointers and unsafe code.

A C# pointer is nothing but a variable that holds the memory address of another type.

Syntax of Pointers in C#

type *var_name;
// example is
int *var = & x;

Unsafe Codes

The Pointers in C# statements can be executed in an unsafe context. The statements marked as unsafe by using the unsafe keyword and this piece of code will run outside the control of Garbage Collector. How we can unsafe code let’s check below:

public class Program
    {
        static unsafe void Main(string[] args)
        {
            int w = 76;
            int* ptr = &w;
            Console.WriteLine((int)ptr);
            Console.WriteLine(*ptr);
        }
    } 

How to run unsafe codes

  • Open Visual studio and create your console application
  • Right click on solution and select property option.
  • Go to the build tab (as shoe in below image)
  • Check the “Allow unsafe code” option.
Pointers in C#

Safe VS unsafe code

Safe codes in C# runs under the Common Language Runtime’s supervision (CLR) while Un-safe codes always execute outside the management of the CLR.

Conclusion:

Unsafe code execution option is only available for C# whereas in C or C++, pointers code runs under safe code.

Pointers in C# shows the memory address and execute unmanaged codes, as we have discussed above. The reason behind using the unsafe statements is that the garbage collector does not track memory addresses in an unmanaged environment.

Video on Pointers in C#:

In this article, we’ve learned how to use Pointers in C#. You can also check our related article Pointers and unsafe code. I believe after reading this article you’ll be able to use this in your daily development practices. You can also check more on Microsoft Learn.

Are you willing to check more on C# then please visit HERE

Leave a Reply

Your email address will not be published. Required fields are marked *