Pointer (Unsafe Code)
Pointer (Unsafe Code)
What is Pointer ?
• C# supports pointers in a limited extent.
• Syntax:
– unsafe Context_declaration
Example1
using System;
class Program
{
static void Main()
{
unsafe
{
int x = 10;
int* ptr;
ptr = &x;
Console.WriteLine("Inside the unsafe code block");
Console.WriteLine("The value of x is " + *ptr);
}
}
}
Example2
using System;
class Program
{
static unsafe void Main()
{
int x = 10;
int* ptr;
ptr = &x;
Console.WriteLine("Inside the unsafe code block");
Console.WriteLine("The value of x is " + *ptr);
}
}
Example of method
using System; class demo
class Program {
{ static void Main(string[] args)
public void show() {
{ Program p1=new Program();
unsafe p1.show();
{ }
int x = 10; }
int* ptr;
ptr = &x;
Console.WriteLine("Inside the unsafe code block");
Console.WriteLine("The value of x is " + *ptr);
}
}
}
Example of swap two value
using System;
class TestPointer
{
public unsafe void swap(int* p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}
public unsafe static void Main()
{
TestPointer p = new TestPointer();
int var1 = 10;
int var2 = 20;
int* x = &var1;
int* y = &var2;
• If you are using Visual Studio IDE then you need to enable use of
unsafe code in the project properties.
• To do this −
• Open project properties by double clicking the properties node in
the Solution Explorer.
• Click on the Build tab.
• Select the option "Allow unsafe code".