Hide private field from reflection in .net

I have a class that performs some I / O on the entire disk volume. By sensitive I mean, if the operation goes wrong, it could potentially damage the target volume.

During some testing after the release, I found that the process can be ruined by using reflection to manipulate private fields. The class is not sealeddesigned, so library users can create derivatives.

Is there a way to protect private members to prevent change through reflection (from derived or consumer code)?

UPDATE: I found a comment from Hans Passant on an old mention issue[ReflectionPermission] . Look at it now.

+4
source share
4 answers

Unable to hide your field from Reflection. It can be used to access and manage any type field. There are steps that you can take as obfuscation, which make it difficult to define fields and, in turn, more difficult to change through Reflection. But this is just a speed hit. A certain developer can use Reflection to beat any work that you have.

+7
source

Short answer: None .

You cannot prevent people from communicating with your program if they have privileges.

+4
source

I believe your best efforts will be to obfuscate the code. Otherwise, you will not be able to prevent someone from using reflection to reflect a little.

There is this post that can give you some idea of ​​how you want to continue.

+3
source

Privatejust for developers consuming your class. You cannot prevent his access through reflection.

+2
source

Source: https://habr.com/ru/post/1531000/


All Articles