csharp / expert
Snippet
Decoupled Unit Verification through Unsafe Private Linkage
C# 12 introduced UnsafeAccessor, providing a high-performance way to access private members for testing. Unlike Reflection, it is checked by the JIT compiler and has zero runtime overhead, making it ideal for verifying internal state in unit tests.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Runtime.CompilerServices;public class InternalVault{private string _secretToken = "init_v1";}public static class VaultInspector{[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_secretToken")]public static extern ref string GetToken(InternalVault vault);}// Test Contextvar vault = new InternalVault();ref string token = ref VaultInspector.GetToken(vault);token = "overridden_for_test"; // Direct private field modification
Breakdown
1
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_secretToken")]
Instructs the compiler to link this extern method to a private field.
2
public static extern ref string
Returns a reference to the field, allowing both reading and writing.