C# Unsafe Keyword

Star (asterisk) character

Some things are necessary evils. They are essential yet fraught with problems. The unsafe context in the C# programming language is one of these things. It is used to implement certain algorithms in an efficient way, but more often leads to unstable and hard-to-understand source code—code that does not belong in important projects.

Interfacing with the operating system, accessing a memory-mapped device, or implementing a time-critical algorithm may not be possible or practical without access to pointers. Hejlsberg et al., p. 623

Bugs. See Unsafe code
(C# specification index) Hejlsberg et al., p. 730

Modifier

.NET Framework information

As an introduction to unsafe code, this program shows how you can use the unsafe modifier, and also the fixed keyword, to use char* pointers on a string's buffer. The fixed keyword asserts that the memory location should not be moved in memory. The '\0' character is used by the .NET Framework to terminate a string.

Program that uses unsafe code [C#]

using System;

class Program
{
    unsafe static void Main()
    {
	fixed (char* value = "sam")
	{
	    char* ptr = value;
	    while (*ptr != '\0')
	    {
		Console.WriteLine(*ptr);
		++ptr;
	    }
	}
    }
}

Output

s
a
m

Block

In addition to the use of the unsafe keyword as a modifier, you can use an unsafe block inside a method, as shown in the next example, which has an equivalent result.

Program that uses unsafe block [C#]

using System;

class Program
{
    static void Main()
    {
	unsafe
	{
	    fixed (char* value = "sam")
	    {
		char* ptr = value;
		while (*ptr != '\0')
		{
		    Console.WriteLine(*ptr);
		    ++ptr;
		}
	    }
	}
    }
}

Output
    (Same as first example.)

Note: If you try to compile these programs, you will get this error: "Unsafe code may only appear if compiling with /unsafe". To solve this in Visual Studio 2010, go to Project > Properties > Build and check "Allow unsafe code".

Fixed

Square abstract illustration

We show how you can use fixed buffers in the C# language inside an unsafe context. With a fixed buffer, you can write an read raw memory without any of the managed overhead. We additionally reveal how you can use the fixed statement to create an unmovable memory block.

Fixed Buffer Struct: Unsafe Fixed Statement

Stackalloc

The C# programming language

The C# language includes the stackalloc operator in addition to the regular allocators. This memory is freed when the enclosing function returns. Stackalloc can be useful for external DLL calls; it is not usually a good optimization in managed code.

Stackalloc Operator

Examples

Finally, there are several examples of unsafe code also on this site. These do not focus on unsafe features in particular, but rather instances where unsafe code could be used.

GetHashCode String Implementation Application_BeginRequest ExampleProgramming tip

Tip: The best thing to do with unsafe code is to avoid it. This applies unless you know exactly what you are doing and are willing to put a lot of effort into your solution.

Summary

Unsafe code does not make a significant performance difference in most programs. Its most important usage is directly inside the .NET Framework, where it is used as optimization for critical methods such as GetHashCode and string copying.

.NET