views:

291

answers:

4

Hi

I used reflection many times before on public methods but never realized that private methods can be invoked too. See the link

I am still thinking why is that allowed in the first place? Isn't that going to break the rule of "private" being "private"?

puzzled AJ

+1  A: 

Yep, it does break the rule. I'd almost never pass code during a review if someone did this.

Using reflection to call a method is slllloooow, not type-safe, and breaks easily if the underlying class has the private methods reworked.

So in short, I agree, it's a bad idea!

Will
strange. why they would allow that..... suddenly, world is safe no more ;)
AJ
+1  A: 

private in C# is truly only part of the language specification; in the C# language, as well as in the Visual Basic language or any other sensible .NET language (including CIL, what all the .NET languages compile to) one is prevented from accessing a private (or protected, if you're not within a derived class) member in the language. However, just because the language doesn't support publicly accessing private or protected members doesn't mean the underlying framework can't provide access to those members.

This is one of those cases where one typically shouldn't be using workarounds like reflection to access or modify private or protected members, but the framework allows one to anyway. Generally, you should have a very good reason to access private or protected members; one such reason, for example, is implementing a serializer that needs to look at the object's internal state to properly serialize the object. If you're not doing something like that, you should truly look at reimplementing the class you're poking around inside, so that you don't need to use reflection in your program.

Adam Maras
+1  A: 

This is advanced power you get from the framework. It is very uncommon to use it in production code for invoking methods, it breaks the advantages of members hiding.

There are some places where it can be useful:

  • Legacy code testing - For example, assume you are working with legacy code and you want to cover it with unit tests. If you're not allowed to change the code and you want to test small part of the functionality invoking private methods is useful.
  • Hacks in production code - I encountered once a bug in 3rd party control where in some scenario a private cleanup was not done. Using private invoke I could work around it.

There is nothing wrong with the framework providing this functionality, but using it where it's not a must is wrong.

Elisha
+2  A: 

This is only allowed when the code is running under full trust (or with the relevant permission). Otherwise, a MethodAccessException will be thrown.

The framework is perfectly able to restrict access appropriately - it just doesn't do so when you're running under full trust or when you have specific permissions. See "Security Considerations for Reflection" for more details of when you're able to do this.

Jon Skeet