Skip to content
This repository has been archived by the owner on May 27, 2024. It is now read-only.

Backport to older .NET versions with IgnoresAccessChecksToAttribute? #2

Closed
BlinD-HuNTeR opened this issue Sep 21, 2023 · 2 comments
Closed

Comments

@BlinD-HuNTeR
Copy link

Even though UnsafeAccessorAttribute is new to .NET 8, accessing private members with no overhead has always been possible in older .NET runtimes through the use of IgnoresAccessChecksToAttribute. That are a couple of NuGet packages (like MakeTypesPublic) that provide MSBuild targets to automate all steps required to use it.

My suggestion is that, it would be very nice if the Source Generator could provide a fallback, and generate proxies that use this attribute instead, when building in .NET versions where UnsafeAccessorAttribute is not available.

Unfortunately, though, you can't use IgnoresAccessChecksToAttribute to unlock access inside your own assembly. But I suppose if someone wants that, they can just edit their own source code and make things internal, so this shouldn't be an issue.

@AArnott
Copy link
Contributor

AArnott commented Sep 21, 2023

I don't see how IgnoresAccessChecksTo would work in at all the same model as this source generator.
It would require a different assembly to be generated that includes the attributes and the code to call the private code.

AFAIK IgnoresAccessChecksTo can only be meaningfully used by IL emitting generators (i.e. dynamic code gen) because the C# compiler itself does not honor it. Even if you have a C# project that includes this attribute, C# won't let you access the private members. I use this attribute myself, but only when the C# compiler doesn't apply, because I'm emitting IL directly.

@neuecc neuecc closed this as completed Sep 24, 2023
@BlinD-HuNTeR
Copy link
Author

AFAIK IgnoresAccessChecksTo can only be meaningfully used by IL emitting generators (i.e. dynamic code gen) because the C# compiler itself does not honor it.

It's true that the compiler does not honor it, but it's possible to compile your code against publicized asemblies, so that all members appear as public at compile-time (at runtime you use the original assemblies, and the attribute will do its work).

The NuGet package I mentioned uses MSBuild targets to automatically generate such publicized assemblies and reference them in your project. This way it's possible to have a source-based approach.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants