Tag Archives: unsafe

Using Unsafe in C#

Using Unsafe in C#

First we have to allow unsafe keyword in project.
Right click on project in Solution Explorer. Properties ->Build -> Allow unsafe code .we have to enable this properties.
Now we can write c++ codes in c# with unsafe.

using System.Windows.Forms;

unsafe static void MultiplyByTwo(int* intVal)
{
	*intVal = *intVal * 2;
}

private void CallUnsafeFunction()
{
	int intVal = 5;
	unsafe
	{
		MultiplyByTwo(&intVal);
	}

	MessageBox.Show(intVal.ToString());
}