4

Investigating .NET Reflection API I understood that it is possible to change private fields/properties values using reflection and security is controlled by reflection permissions in that case. My question is how to control whether code can have an access to private fields or not? From MSDN:

To allow code to invoke any nonpublic member: Your code must be granted ReflectionPermission with the ReflectionPermissionFlag.MemberAccess flag.

How can I make my class private fields to be non-visible to code that uses reflection? What are the best practices on doing that?

Qué Padre
  • 2,005
  • 3
  • 24
  • 39

2 Answers2

3

ReflectionPermission is a permission granted to the code using reflection, not to the code being reflected.

As a developer, there is nothing you can do to prevent your code from being reflected. You could use obfuscation, but that only makes reflection harder, not impossible.

As a system administrator, you might be able to prevent code that requires ReflectionPermission from running by enforcing an appropriate security policy for the machine, but, if I understood your question correctly, this is not what you are looking for.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
0

See the links in the comments but the short answer is: ultimately you can't restrict someone from using reflection on your code.

The links from the comment that explains it well: How can I restrict reflection for certain assemblies?

Community
  • 1
  • 1
Szymon
  • 42,577
  • 16
  • 96
  • 114