DCSIMG
Reflection and Privates - Pavel's Blog
Sign in | Join | Help

Pavel's Blog

Pavel is a software guy that is interested in almost everything
software related... way too much for too little time

Reflection and Privates

During teaching of .NET reflection topics, I mention that using reflection, one can get to the private members of types, and even invoke those members dynamically.

I sometimes get the response in the lines of - how is this possible? What's the point of putting something as private if it's exposed through reflection?

The answer to the "dilemma" is that applications usually run with FullTrust permissions, which means they actually can do anything, including poking in other's privates. But, doing reflection requires having the ReflectionPermission permission with an appropriate flag (ReflectionPermissionFlag enumeration) which may not be granted in partial trust scenarios. The flag allows restricting reflection to enumerating public elements only, allowing dynamic invocation of members and more.

Comments List

# re: Reflection and Privates

Published at Tuesday, July 08, 2008 2:55 PM by Ophir_A  

This is nice, but...

For my opinion, it is not right to relate the OO Concept to Security issues.

If you are dealing with reflection which is a Meta code level its ok to get deal with the entire interface. Invoking a method using reflections is not the "OO way" or a "code safe" way to use the code.

For example in c++ a user of class can modify in the .H file members from private to public (like changing the Meta code) and call a private function.

This is like using a device, not like the producer tells you to, so you don’t have a warranty…

# re: Reflection and Privates

Published at Tuesday, July 08, 2008 3:25 PM by pavely  

You are correct, but you don't do dynamic invocation to bypass some OO thing. usually it's done because you have to. For example, the VS designer changes property values using reflection - how else would it be able to do that?

By the way, in C++ the Cheshire cat idiom allows you to hide part of your H file, so nobody can change the privates to publics...

# re: Reflection and Privates

Published at Tuesday, July 08, 2008 8:31 PM by Sasha Goldshtein  

...while we're at it, you can always write (ugly and fragile) code in C++ that will rely on the internal field order to access fields that are private by their memory location.

# re: Reflection and Privates

Published at Wednesday, July 09, 2008 9:10 AM by pavely  

in C++ there's no actual limit to the amount of havoc we can wreak in our code...

Leave a Comment

(required) 
(
required
)
 
(optional)
(required) 

Enter the numbers above: