Skip to content

Instantly share code, notes, and snippets.

@mgravell
Created September 14, 2023 05:48
Show Gist options
  • Save mgravell/bf8908cb99e99bfda2e5513c02627efc to your computer and use it in GitHub Desktop.
Save mgravell/bf8908cb99e99bfda2e5513c02627efc to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
Bar b = CreateBar(42); // invoke a private .ctor
ref int x = ref GetBarX(b); // read field *ref*
Console.WriteLine(x); // deref field value
x = 17; // rewrite a private readonly field
Console.WriteLine(b.A); // 17
[UnsafeAccessor(UnsafeAccessorKind.Constructor)]
static extern Bar CreateBar(int a);
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "x")]
static extern ref int GetBarX(Bar bar);
file class Bar
{
private readonly int x;
public int A => x;
private Bar(int a) => x = a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment