C# Access private property backing field using Unsafe Accessor
One less-known feature of the UnsafeAccessorAttribute
is that it also allows you to access auto-generated backing fields of auto-properties – fields with unspeakable names.
The way to access them is very similar to accesing fields, the only difference being the member name pattern, which looks like this:
<MyProperty>k__BackingField
Code language: plaintext (plaintext)
Let’s take the following class as an example:
class Foo
{
private string InstanceProperty { get; set; } = "instance-property";
}
Code language: C# (cs)
Below you have the unsafe accessor for the backing field of this property and examples on how to read the private backing field and how to modify it’s value.
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<InstanceProperty>k__BackingField")]
extern static ref string InstancePropertyBackingField(Foo @this);
var instance = new Foo();
// Read
_ = InstancePropertyBackingField(instance);
// Modify
InstancePropertyBackingField(instance) = Guid.NewGuid().ToString();
Code language: C# (cs)