In C, other than Value Type and Reference types we have one more category called Pointer Types. Pointers in C# are used to control the CLR memory management schema that means by passing the CLR memory management schema and take control into our own hands.
If you are going to use C# Pointers, you have to allocate the memory for each of your variable and .Net runtime don't know about your intension. So be careful while using pointers because if you mismanage the usage of pointers then your application will not work properly.
There are C# operators are there to use while working with pointers, those are listed below.
* is used to create the pointer variable, represents the direct location in memory.
& is used to get the address of the variable.
-> is used to access the fields of a type that is represented by a pointer.
[] is used to allows you to index the slot pointed to by a pointer variable.
++, -- are increment and decrement operators can be applied to pointer types.
+, - are used for the addition and subtraction operators can be applied to pointer types.
==, !=, <, >, <=, => are used for the comparison and equality operators can be applied to pointer types.
stackalloc keyword is used to allocate C# arrays directly on the stack.
fixed keyword can be used to temporarily fix a variable so that its address may be found.
All those operators and keywords are used in unsafe context. Whenever you are using C# pointers you have to inform C# compiler as a unsafe code because you are going to bypass the CLR memory management schema. You can inform the C# compiler as unsafe code you using /unsafe flag as argument through the command prompt. Execute csc /unsafe *.cs from command prompt. You can mention as unsafe code from visual studio also, right click on Solution explorer -> go to Build and select "Allow unsafe code" option as shown below.
Whenever you are going to use C# pointers in your code, you have to mention block of code as unsafe by using unsafe keyword. Within the block mentioned by unsafe keyword only you can use C# pointers as shown below.
using System;
namespace CSharpPointers
{
class Program
{
static void Main(string[] args)
{
unsafe
{
//you can have pointers code here
int i1;
int* iPointer = &i1;
*iPointer = 100;
Console.WriteLine("The value of i1 variable: " + i1 + "\n");
Console.WriteLine("The address of i1 variable: " + (int)&iPointer);
Console.ReadLine();
}
}
}
}
You can mention unsafe keyword for methods, structures ... etc as show below.
public unsafe struct Employee
{
public int Id;
public Employee* EmpName;
public Employee* EmpSal;
}
unsafe decimal GetEmpSal(int Id)
{
decimal dSal = 0;
return dSal;
}
Methods mentioned by unsafe keyword can only accessed from unsafe environment only.