capypad
0 day streak
csharp / expert
Snippet

Unsafe Accessors for Zero-Overhead Private Member Access

Introduced in C# 12, Unsafe Accessors allow code to access private members of other classes without the performance penalty of Reflection. By using the [UnsafeAccessor] attribute on an extern static method, the compiler generates a direct IL reference to the private field or method, making it as fast as a public access while bypassing visibility constraints.

snippet.csharp
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Runtime.CompilerServices;
 
public class DataBuffer {
private int _secretId = 42;
}
 
public class Accessor {
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_secretId")]
public static extern ref int GetSecretId(DataBuffer buffer);
}
 
// Usage
var buffer = new DataBuffer();
ref int id = ref Accessor.GetSecretId(buffer);
id = 100; // Directly modifies private field
Breakdown
1
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_secretId")]
Instructs the compiler to link this method to a private field named _secretId.
2
public static extern ref int GetSecretId(DataBuffer buffer);
Defines an external method that returns a reference to the private integer field.
3
ref int id = ref Accessor.GetSecretId(buffer);
Retrieves the reference, allowing direct modification of the private state.