How to use Pointer in CSharpHow to use Pointer in c#
Introduction
To understand the article first you have to know that what is managed code and what is unmanaged code so let’s start with these two types of coding:
Managed code is that code which executes under the supervision of the CLR. The CLR is responsible for various housekeeping tasks, like:
• managing memory for the objects
• performing type verification
• doing garbage collection
The user is totally isolated from the how's of the above mentioned tasks. The user doesn't get to manipulate the memory directly, because that is done by the CLR.
On the other hand, unmanaged code is that code which executes outside the context of the CLR. A typical C++ program which allocates memory to a character pointer is another example of unmanaged code because you as the programmer are 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
If you notice, all this housekeeping is done by the CLR, as explained above, relieving the programmer of the burden.
Unsafe code is a kind of cross between the managed and unmanaged codes It executes under the supervision of the CLR, just like the managed code, but lets you address the memory directly, through the use of pointers, as is done in unmanaged code.
You might be writing a .NET application that uses the functionality in a legacy Win32 DLL, whose exported functions require the use of pointers. That's where unsafe code comes to your rescue.
The use of pointer in C# is defined as a unsafe code. So if we want to use pointer in C# the pointer must be present in the body of unsafe declaration. But pointer does not come under garbage collection.
unsafe
{
int a, *b;
a = 100;
b = &a;
Console.WriteLine("b= {0}",b);
//returns b= 100
}
See the below program for swapping of two numbers using pointer in C#.
class Swapping
{
//declaring pointers inside unsafe code
unsafe public static void UnsafeSwap(int* i, int* j)
{
int temp = *i;
*i = *j;
*j = temp;
}
static void Main(string args[])
{
// Values for swapping.
int i = 101, j = 200;
// Swap values using pointer
Console.WriteLine("Values before swap: i = {0}, j = {1}", i, j);
unsafe //passing the values to unsafe code
{
UnsafeSwap(&i, &j);
}
Console.WriteLine("Values after swap: i = {0}, j = {1}", i, j);
}
Output:-
Values before swap: i = 100, j = 200
Values after swap: i = 200, j = 100