TheDeveloperBlog.com


C# Unsafe Keyword: Fixed, Pointers

Unsafe. A volcano emits smoke. A knife glides through the night air. These things are dangerous. They are unsafe. In C#, unsafe things access memory directly.


A context. The unsafe context allows unsafe memory use. It is used to implement algorithms in an efficient way. This is a modifier. Often we must also enable "unsafe" code in Visual Studio.


An example. This program adds the unsafe modifier and fixed keyword to use char* pointers on a string's buffer. Fixed asserts that the memory location should not be moved in memory.

Tip: The '\0' character is used by the .NET Framework to terminate a string. We need to know this only for unsafe code.

CharStrings
Based on:

.NET 4

C# program that uses unsafe code

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

Unsafe block. We can also use an unsafe block inside a method. This has an equivalent result. This spaces code out and emphasizes the unsafe modifier more.

Note: If you try to compile these programs, you will get this error: "Unsafe code may only appear if compiling with /unsafe".

And: To solve this in Visual Studio, go to Project > Properties > Build and check "Allow unsafe code".

C# program that uses unsafe block

using System;

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

Output

s
a
m

Fixed. We use fixed buffers inside an unsafe context. With a fixed buffer, you can write and read raw memory without any of the managed overhead.

Fixed Buffer Struct

And: We use the fixed statement to create an unmovable memory block. This allows pointer access.

Fixed

Stackalloc. This operator replaces the regular allocators. This memory is freed when the enclosing function returns. Stackalloc can be useful for external DLL calls.

Caution: Stackalloc is not usually a good optimization in managed code. It introduces some overhead.

Stackalloc

Some examples. These examples may be helpful in understanding. They do not focus on unsafe features in particular, but rather instances where unsafe code could be used.

GetHashCodeApplication_BeginRequest

Some comments. The best thing to do with unsafe code is to avoid it. Unsafe code makes programs slower. It makes them harder to understand.

However: This applies unless you know exactly what you are doing and are willing to put a lot of effort into your solution.


Research. Why do we need unsafe code? In my research, I found it is needed for using certain external systems. And sometimes a "time-critical" piece of code is needed.

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.

The C# Programming Language

A pointer type is a compile-time description of a value whose representation is a machine address of a location.

The CLI Annotated Standard

A summary. Unsafe code is rarely needed. Its most important use is inside the .NET Framework. There it optimizes critical methods such as GetHashCode and string copy routines.