Skip to content
Latchkey

C# "CS0227: unsafe code requires AllowUnsafeBlocks" in CI

CS0227 means the code uses an unsafe context (pointers, fixed, stackalloc in some forms) but the project does not enable unsafe compilation. The compiler refuses unsafe code unless AllowUnsafeBlocks is true.

What this error means

The build fails with CS0227 at the unsafe construct. It reproduces every run until the project setting is added.

dotnet
Interop/Native.cs(11,9): error CS0227: Unsafe code may only appear if compiling with /unsafe

Common causes

AllowUnsafeBlocks is not enabled

The project uses unsafe code but the csproj never set <AllowUnsafeBlocks>true</AllowUnsafeBlocks>, so the compiler blocks it.

Unsafe code added to the wrong project

A pointer-based helper was placed in a project that intentionally disallows unsafe code.

How to fix it

Enable unsafe blocks for the project

  1. Add the property to the project that contains the unsafe code.
  2. Confirm only that project enables it, to keep the rest of the solution safe.
  3. Rebuild.
csproj
<PropertyGroup>
  <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

How to prevent it

  • Isolate unsafe interop in a dedicated project with the flag set.
  • Review whether managed alternatives (Span, Memory) avoid the need for unsafe.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →