Improving C# Memory Safety
6 hours ago
- #memory safety
- #unsafe keyword
- #C#
- C# 16 introduces a new memory safety model redesigning the 'unsafe' keyword to mark a contract with caller obligations, rather than just a scope for pointer operations.
- The new model requires unsafe operations to be enclosed in 'unsafe { }' blocks, with member signatures using 'unsafe' to propagate obligations up the call graph, and safety boundaries suppress unsafety by discharging obligations.
- Safety documentation via '/// <safety>' blocks is encouraged for unsafe members, and an analyzer will flag missing documentation.
- The changes will be opt-in via a project property, with plans to release as a preview in .NET 11 and production in .NET 12, and templates will enable it similarly to nullable reference types.
- The model enhances visibility and reviewability of safety contracts, aims to improve supply chain security, and aligns C#'s approach with Rust and Swift for consistency in unsafe code patterns.