Raheel Khan
Raheel Khan

Reputation: 14777

Hiding a private field from reflection in .net

I have a class that performs some sensitive I/O operations across an entire disk volume. By sensitive I mean if the operation goes wrong, it can potentially corrupt the target volume.

During some post-release testing, I found that the process can be corrupted using reflection to manipulate private fields. The class is not sealed by design so that consumers of the library can create derivatives.

Is there a way to secure private members to prevent modification via reflection (from derived or consumer code)?

UPDATE: I found a comment from Hans Passant to an old question mentioning [ReflectionPermission]. Looking into that now.

Upvotes: 4

Views: 1473

Answers (4)

JaredPar
JaredPar

Reputation: 754525

There is no way to hide your field from Reflection. It can be used to access and manipulate any field on a type. There are steps you can take like obfuscation which make it harder to identify fields and in turn harder to change via Reflection. This is only a speed bump though. A determined developer can use Reflection to beat any work arounds you have

Upvotes: 7

IAbstract
IAbstract

Reputation: 19871

I believe your best effort is going to be in obfuscating the code. Otherwise, you cannot stop someone from using reflection to mar things up a bit.

There is this post which may give you some idea on how you want to proceed.

Upvotes: 3

Habib
Habib

Reputation: 223187

Private is just private to developers consuming your class. You cannot prevent its access via reflection.

Upvotes: 2

nvoigt
nvoigt

Reputation: 77285

Short Answer: No.

You cannot stop people from messing with your program if they have the privileges.

Upvotes: 4

Related Questions