Feb 10, 2010

Using unsafe code in C# in easy manner

class ClassName
{

//pointer

unsafe int * ptr;

unsafe void MyMethod()
{
//you can use pointers here
}

}

To declare unsafe local variables in a method, you have to put them in unsafe blocks as the following:

static void Main()
{

//can't use pointers here

unsafe

{

//here you can declare and use pointer

}

//can't use pointers here
}

Example
=======

static void Main()
{

int var1 = 5;

unsafe
{

int * ptr1, ptr2;

ptr1 = &var1;

ptr2 = ptr1;

*ptr2 = 20;

}

Console.WriteLine(var1);
}

OUTPUE: 20

No comments:

Post a Comment