It is a very small and basic article showing that how can we use pointers in C#. I am posting this article because most of the people think that C# does not allow the use of pointers. In this example I will create a small function which will changes the value of a variable using the Pointers. So lets start:
First of all make a simple console application. Copy the following function:
unsafe private static void UseUnsafeCode()
{
int count = 10;
int* p;
p = &count;
System.Console.WriteLine("Value of count before changing=" + count.ToString());
*p = 25;
System.Console.WriteLine("Value of count after changing=" + count.ToString());
System.Console.ReadLine();
}
Now call the above function in the main program.
Please make sure to allow the compilation of safe code in the property of the project.
The sample code will look something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
UseUnsafeCode();
}
unsafe private static void UseUnsafeCode()
{
int count = 10;int* p;
p = &count;
System.Console.WriteLine("Value of count before changing=" + count.ToString());
*p = 25;
System.Console.WriteLine("Value of count after changing=" + count.ToString());System.
Console.ReadLine();
}
}
}
In the above example I have made a function in which I have declared two variables. The first one is count and its data type is int and the second is an int pointer. Also in the code I have changed the value of count variable using the pointer p variable. The output is given below:
Value of count before changing = 10
Value of count after chaning = 25