As a lead, would you allow unsafe code in a C# codebase, and if so where, under what review, and how would you enforce the boundary?
answer
- measure before permitting
- one small assembly
- safe API on the outside
- the switch misses Unsafe
basics
~20 sAllow it only where a measurement shows safe spans cannot match it: in one small assembly with AllowUnsafeBlocks, behind a validated span-based API, with mandatory review and edge-case tests, and with Unsafe and MemoryMarshal banned elsewhere because the switch misses them.
solid answer
~50 sI would default to no: `AllowUnsafeBlocks` off everywhere, because spans, `stackalloc` into spans, `[InlineArray]` and the vectorized base class library cover most needs in safe code. Unsafe code earns an exception when a benchmark shows a hot path that safe code cannot match, or when a pointer-shaped API leaves no choice. Then it lives in one small internal assembly with the switch on, behind a public surface of spans and arrays that validates every length before the unsafe part runs. Every change there gets a second reviewer who knows the invariants, a written comment explaining why each access is in bounds, and tests at lengths 0, 1, odd sizes and the maximum. Because `Unsafe`, `MemoryMarshal` and `CollectionsMarshal` compile without the switch, the policy also needs an analyzer that bans them outside that assembly. Each exception is re-measured on runtime upgrades and deleted when safe code catches up.
go deeper
Know that unsafe code needs the AllowUnsafeBlocks switch and that teams restrict it because it can corrupt memory.
Explain which C# features the switch gates and why Unsafe and MemoryMarshal slip past it.
Show how you would contain an unsafe hot path: a safe facade, validation before entry, edge-case and differential tests.
Set the policy: default off, measured exceptions in one assembly, analyzer-enforced bans, required reviewers, and deletion when the gain disappears.
## What counts as unsafe code in C# A policy has to name its target, and in C# there are two kinds: - **Code the compiler gates.** Pointer types, `&` and `*`, the `fixed` statement, `stackalloc` into a pointer, fixed-size buffers, function pointers (`delegate*`, C# 9), and `[SkipLocalsInit]`. All of it needs `unsafe` plus `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>`, which is off by default, so it shows up in a project file and in review. - **Code the compiler does not gate.** `System.Runtime.CompilerServices.Unsafe` (`Add`, `As`, `ReadUnaligned`), `MemoryMarshal` (`Cast`, `CreateSpan`, `GetReference`, `GetArrayDataReference`) and `CollectionsMarshal` (whose `AsSpan` exposes a `List<T>`'s backing array, to which items should not be added or removed while the span is in use) skip bounds, type or ownership checks, yet their signatures use `ref` and spans, so they compile with the switch off. A rule that says "no unsafe code" and enforces it with the switch alone leaves the second group wide open. ## When an exception is justified The honest default is that most C# never needs either group. Safe tools now cover much of what used to require pointers: spans over arrays, strings and stack memory, `stackalloc` into `Span<T>`, `[InlineArray]` for fixed-length inline storage, `BinaryPrimitives` for byte order, and base class library methods that are already vectorized. Reasons that do justify unsafe code: 1. **A measured hot path** (codecs, image kernels, parsers, checksums) where a profiler and a benchmark show bounds checks or copies that the JIT did not remove, and the gain matters to the product. 2. **An API shaped around pointers** where the alternative is worse. Native interop itself, P/Invoke and marshalling, is governed by the material on the .NET runtime. 3. **Reinterpreting binary data** in place, where copying would dominate the cost. "It might be faster" is not on the list: the benchmark, kept in the repository, is the entry ticket. ## How to contain it 1. **One small internal assembly**, the only project with `AllowUnsafeBlocks` set; a shared build props file keeps it `false` for every other project. 2. **A safe facade.** Public methods take spans or arrays, validate lengths, alignment and byte order, and only then enter the unsafe part, so callers cannot violate its preconditions. 3. **Local justification.** Every unsafe block or `Unsafe` call carries a comment stating why each access is in bounds. The documentation for the C# 15 preview memory-safety model formalises the same idea with `// SAFETY:` comments and members marked as requiring unsafe callers; it is preview, not shipped. 4. **Short pins and bounded stacks.** `fixed` scopes kept tight, `stackalloc` sizes capped by constants. ## Review and verification - **Required reviewers** for that folder who know the invariants; a change elsewhere that touches it is routed to them. - **Tests at the edges**: empty input, one element, lengths that are not a multiple of the word size, the maximum size, and misaligned slices. - **Differential tests** comparing the unsafe path with a simple safe reference implementation on random inputs, which catches the off-by-one that unit tests miss. - **Benchmarks kept with the code** and re-run on each runtime upgrade. When the JIT or the library catches up, the unsafe code is deleted; it is a cost the team pays only while it earns its keep. ## Enforcing the boundary | Control | Catches | Misses | |---|---|---| | `AllowUnsafeBlocks` off by default | pointers, `fixed`, `stackalloc` to pointer, `[SkipLocalsInit]` | `Unsafe`, `MemoryMarshal`, `CollectionsMarshal` | | A banned-API analyzer or a custom Roslyn analyzer listing those classes | calls to the listed types outside the allowed assembly | APIs nobody added to the list | | Required reviewers on the unsafe folder | logic errors a human can see | anything merged without review | | Differential tests and fuzzing | out-of-bounds and truncation bugs | paths the inputs never reach | No single control is enough; the combination makes unsafe code rare, visible and owned. ## The trade-off a lead owns Allowing unsafe code trades **speed for a class of bugs that safe C# normally rules out**: memory corruption that appears far from its cause, data-dependent crashes, and security exposure when the input is hostile. Forbidding it entirely can cost real performance in a product whose value is throughput. The defensible position is a narrow, measured, reviewed exception with an exit plan, not a blanket yes or no.
- A pull request says it adds no unsafe code because AllowUnsafeBlocks is still false, but it calls MemoryMarshal.CreateSpan; how do you respond?The switch only gates pointer syntax. `CreateSpan` trusts the length it is given and the compiler does not validate the returned span's lifetime, so it can expose memory past the data or after it is gone. I would treat it as unsafe code under the same policy: move it into the allowed assembly, or replace it with a checked span API.
- When would you remove unsafe code that the team already relies on?When its benchmark no longer shows a meaningful gain over a safe version, which often happens after runtime upgrades improve bounds-check elimination or vectorize a library method. Keep the safe reference implementation used in differential tests; if it now performs within budget, it becomes the production path and the unsafe code is deleted.
- Should SkipLocalsInit be allowed outside the unsafe assembly in a C# codebase?No. It needs `AllowUnsafeBlocks` for a reason: with zeroing removed, code that reads a `stackalloc` buffer before writing it sees leftover stack bytes, which can leak data or cause nondeterministic bugs. It belongs with the other unsafe code, with the same review and a measurement showing the zeroing cost matters.
- Unsafe code is always faster, so hot paths should use pointers by default
- Keeping AllowUnsafeBlocks off guarantees the codebase has no memory-unsafe calls
- Unsafe code is fine anywhere as long as it has unit tests
- Spans make unsafe code obsolete, so no exception is ever justified
- Once unsafe code ships it should stay, even when safe code catches up