| Home | Biography | Speaking | Articles | Books | Music |
I’m doing a couple of talks at Live 360 Orlando 2026, one of which is a Fast Focus called “Doing Fun Things With Unsafe Code”. In that talk, I’ll show a number of APIs in .NET that, while “risky” in various ways, can make your code faster and more efficient. One of them is with the [UnsafeAcccessor] attribute. As I was building the demo code, I started to noticed something. Namely, using this attribute definitely makes non-public member usage faster and consume less memory than the Refection API counterparts (e.g. MethodInfo and PropertyInfo), but it’s still prone to internal type changes breaking your code at runtime.
So I decided to write SaferAccessors. It’s a source generator that looks at a type, creates all the necessary extern methods to access non-public members, and does it in a way that uses the modern extension declaration in C#. Long story short, once you reference the package, you can write code like this, and it just works:
[assembly: UnsafeAccessorMap(typeof(MethodContent))]
Console.WriteLine(new MethodContent().Compute("Hello"));
public sealed class MethodContent
{
private int Compute(string value) => value.Length;
}
To be clear, I’m not trying to encourage using non-public members from a type. In fact, that should only be done if you have no other choice for the problem at hand. But if you have to go that route, SaferAccessors is faster, and it’ll break at compile-time if member definitions change, not runtime. Also, because of the code that’s generated and the features used within that generated code, this will only work for C# 14 and above.
There’s more information you can find at the GitHub site, so I won’t repeat it all here. Also, the first release is 0.1.0, so there’s more work to be done before I push a 1.0.0 release. For example, generics aren’t supported yet, and that has to be there. I wanted to get a proof-of-concept published first before I tackled generics (it’s not hard, but generics can be a bit tricky). But, if you’re in the boat that you need to use non-public members in a type, you may want to consider using this library.
Happy coding!
Published: 11.04.2026 09:07 AM CST