Saturday, March 06, 2010

What is “unsafe” Keyword in C#.NET

What is "unsafe" Keyword in C#.NET

In C# the value can be directly referenced to a variable, so there is no need of pointer. Use of pointer sometime crashes the application. But C# supports pointer and we can use pointer in C#.

The use of pointer in C# is defined as an 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.

Example:-

unsafe

{

int firstVariable;

int* secondPointerVariable;

firstVariable = 25;

secondPointerVariable = &firstVariable;

Console.WriteLine("secondPointerVariable = {0}", secondPointerVariable);

//returns secondPointerVariable = 25

}


Note: you may get compilation error ("Unsafe code may only appear if compiling with /unsafe") while compiling the above code.

If you' are compiling from the command line then include the /unsafe switch as the error suggests.
If you're compiling from Visual Studio, then look in your project's properties and, under the build tab, check the 'Allow unsafe code' box. It should work fine.

No comments: