In .NET 8 and later, how does [UnsafeAccessor] let C# code read and write a private field like OptionParser._seen, and how does it differ from FieldInfo.SetValue?
answer
- static extern, body from the runtime
- UnsafeAccessorKind.Field
- ref return to write
- a string name the compiler never checks
basics
~10 sYou declare a static extern method marked [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_seen")] that takes an OptionParser and returns ref int; the runtime binds it to the field, with no reflection lookup, boxing or Type object.
solid answer
~30 s`[UnsafeAccessor]`, added in .NET 8, goes on a `static extern` method whose signature describes the target. For a field, the first parameter is the owning instance and the return is `ref int`, so `SeenCount(parser) = 10` writes the private field. The runtime supplies the body. Unlike `GetField("_seen", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(...)`, there is no run-time lookup, no boxing through `object`, and no `Type` flowing into reflection, so it suits trimmed and Native AOT builds. The trade-offs: the name is an unchecked string, a missing member throws `MissingFieldException` or `MissingMethodException` only when the accessor is called, and base classes are never searched.
code
csharp · 31 linesusing System.Runtime.CompilerServices;
var parser = new OptionParser();
ref int seen = ref SeenCount(parser);
seen = 10; // writes the private field through the ref
Console.WriteLine(Describe(parser, "--dry-run")); // --dry-run (seen 11, strict False)
OptionParser strict = Create(true);
Console.WriteLine(Describe(strict, "-v")); // -v (seen 1, strict True)
try { Reset(parser); }
catch (MissingMethodException) { Console.WriteLine("MissingMethodException"); }
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_seen")]
static extern ref int SeenCount(OptionParser p);
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Describe")]
static extern string Describe(OptionParser p, string token);
[UnsafeAccessor(UnsafeAccessorKind.Constructor)]
static extern OptionParser Create(bool strict);
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Reset")]
static extern void Reset(OptionParser p);
class OptionParser
{
private int _seen;
private readonly bool _strict;
public OptionParser() { }
private OptionParser(bool strict) => _strict = strict;
private string Describe(string token) => $"{token} (seen {++_seen}, strict {_strict})";
}go deeper
Know that private members can be reached without reflection on .NET 8 and later, and that doing so breaks the owning type's encapsulation.
Explain the accessor shape: static extern, the UnsafeAccessorKind, the owner as first parameter, and ref returns for writing a field.
Compare it with FieldInfo: no lookup or boxing and no trimming warnings, but unchecked names, no base-class search and failures that appear only when the accessor runs.
Decide where private access is tolerated at all, for example in generated serializers or tests, and require a test that calls each accessor so a dependency update fails fast.
## What `[UnsafeAccessor]` is `System.Runtime.CompilerServices.UnsafeAccessorAttribute`, added in .NET 8, lets code reach a member it cannot normally see (a private field, method or constructor) **without reflection**. You declare a `static extern` method with the signature the member would have, and the runtime supplies its body. There is no `Type` lookup, no `FieldInfo` and no `object` in between; the runtime's design document calls it a zero-overhead mechanism for skipping visibility checks. The attribute takes an `UnsafeAccessorKind`: | Kind | Reaches | Accessor shape | |---|---|---| | `Field` | instance field | first parameter is the owner; return `ref T` to read and write | | `StaticField` | static field | first parameter names the owning type; its value is ignored | | `Method` | instance method | owner first, then the method's parameters | | `StaticMethod` | static method | as above; the first parameter only names the type | | `Constructor` | constructor | the constructor's parameters; returns the new object | The `Name` property gives the member's name; if you omit it, the accessor's own method name is used. For `Constructor`, `Name` must be left unset. ## Reading and writing a private field For a parser with `private int _seen`, the accessor is: ```csharp [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_seen")] static extern ref int SeenCount(OptionParser p); ``` Because it returns `ref int`, `SeenCount(parser) = 10;` writes the field and `int n = SeenCount(parser);` reads it. The snippet sets `_seen` to 10, then calls the private `Describe` method through a `Method` accessor, which increments it and prints `seen 11`. A `Constructor` accessor calls the private `OptionParser(bool)` constructor. For a field or instance method on a **struct**, the runtime requires the first parameter to be passed by `ref`. ## How it differs from `FieldInfo.SetValue` | | `FieldInfo.SetValue` / `GetValue` | `[UnsafeAccessor]` | |---|---|---| | Lookup | `GetField(name, BindingFlags.Instance \| BindingFlags.NonPublic)` at run time | none; the runtime binds the accessor | | Value passing | `object`, so value types are boxed | typed, including `ref` returns | | Type known | from a `Type` value | from the accessor's parameter types | | Missing member | `GetField` returns `null` | `MissingFieldException` or `MissingMethodException` when the accessor is called | | Trimming and Native AOT | a `GetType()` source warns (IL2075) | the SDK's analysis printed no warning for the snippet | The runtime's design document gives the motivation directly: serializers that need to skip visibility checks used to rely on Reflection.Emit or classic reflection, and neither works well for source-generated serializers or Native AOT. `[UnsafeAccessor]` is the zero-overhead replacement, which is why code generators emit it. ## The sharp edges - **The name is not compiler-checked.** `Name = "_seen"` is a string. Rename the field and the code still compiles; calling the accessor then throws `MissingFieldException` (for a method, `MissingMethodException`, as the snippet's `Reset` shows). The runtime design doc suggests `nameof` with `Name` to cope with compiler-mangled names such as those of local functions, but a private member of another type is not visible to `nameof` from outside it. - **No hierarchy walk.** Only the exact type in the first parameter is searched. A private field declared on `OptionParser`'s base class is not found through an `OptionParser` accessor; the call throws `MissingFieldException`. - **The signature must match.** The return type takes part in matching, and a mismatch means the member is not found. If several members still match, the runtime throws `AmbiguousMatchException`. - **Generic targets need .NET 9.** The .NET 9 release notes say generic parameters were not supported in the .NET 8 implementation and were added in .NET 9. - **It is still unsafe.** It breaks encapsulation exactly as private reflection does. The owning type's author never promised that `_seen` exists, so a package update can turn a working accessor into a run-time exception. ## When to reach for it - **Tests or tooling** that must set private state of a type you do not own, where you accept the coupling. - **Source generators and serializers** that need fast, AOT-friendly access to non-public members. - **Replacing a hot `FieldInfo.GetValue` loop** where the target type is known at compile time. When the type is only known at run time, an accessor cannot be written, because it must name the owner in source: through its parameter types, or, since .NET 10, by a string in `[UnsafeAccessorType("Namespace.Type, Assembly")]` on an `object`-typed parameter, for a type you cannot reference. Either way the type is fixed when you compile. That case stays with reflection, and with the trimming annotations that go with it.
- An `[UnsafeAccessor]` for `_seen` worked until a package update; now it throws `MissingFieldException`. Why did the build not catch it?The member name in `Name = "_seen"` is a string that the compiler never resolves; the runtime resolves it and, when the target is missing, the accessor's body throws. If the field was renamed, moved to a base class (accessors do not search base classes) or changed type (the signature must match), the code still compiles and fails on first call. A test that calls every accessor catches it at build time.
- Can `[UnsafeAccessor]` reach a private member of a type discovered at run time with `Assembly.GetTypes()`?No. The accessor must name the owning type in source, because that is how the runtime knows where to look. Its parameter types usually do; since .NET 10, `[UnsafeAccessorType("Namespace.Type, Assembly")]` on an `object`-typed parameter names a type you cannot reference by string, but that string is still fixed when you compile. For types known only at run time you are back to `Type.GetField` or `GetMethod` with `BindingFlags.NonPublic`, plus the trimming annotations that keep those members.
- UnsafeAccessor needs an unsafe block and AllowUnsafeBlocks
- A misspelled member name in UnsafeAccessor fails the build
- UnsafeAccessor searches base classes for the member
- A field accessor returning int can also write the field
- UnsafeAccessor uses reflection internally, so it boxes like FieldInfo.SetValue
Assumes .NET 10; UnsafeAccessorAttribute arrived in .NET 8, and accessors for generic types and methods need .NET 9 or later.