Access private members without reflection (For source generators) #6127
-
Many reflection based tasks can be replaced by source generators, which can provide performance enhancements and also have other benefits for AOT runtimes and code trimming. For example I'm using a source generator to generate custom serialization... But a missing feature is being able to access private and protected members, which is currently only possible with reflection. So I propose an attribute called [AllowAllAccess] that can be applied to a class or a method, which then allowed them to use anything without restrictions. This should not be a security problem, because access is possible with reflection anyway, but the resulting code is much cleaner and not as likely to break because of changes to the code it's calling. The proposed attribute will be beneficial for source generators, but also for testing, where InternalsVisibleTo is commonly used. Illustration of the usecase:
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 11 replies
-
If you're going to explicitly mark the member as allowing all access why would you make it |
Beta Was this translation helpful? Give feedback.
-
Note that this is already possible today using IgnoresAccessChecksToGenerator. Though doing this is unsupported and I haven't tried to use it from a source generator. Making this approach official was rejected in the past (see dotnet/roslyn#20870). I don't know if source generators changed things. |
Beta Was this translation helpful? Give feedback.
-
I believe the last time we discussed this, we felt it was a very bad/smelly thing. I don't see this as having really changed in the interim. If you need access to privates, you should go through reflection, because you're bypassing the language. I don't see why SGs change that. Indeed, the purpose of them is not compile time reflection. It's to silly make it easier to write the code you could already do by hand, but which would a burden. If we don't give you the ability to bypass this, I'm not sure why we'd want to give another party this access. |
Beta Was this translation helpful? Give feedback.
-
I'm happy to see that this is now possible in .NET 8 with the UnsafeAccessor attribute. Guess I'm not the only one that found this useful ;-) |
Beta Was this translation helpful? Give feedback.
I'm happy to see that this is now possible in .NET 8 with the UnsafeAccessor attribute. Guess I'm not the only one that found this useful ;-)