views:

734

answers:

4

Is it possible to override a private method by using Reflection in .NET 3.5?

+1  A: 

Not by using Reflection. You need to use some sort of AOP.

Anton Tykhyy
+4  A: 

Well, it would need to be virtual to be possible to override it (by writing a dynamic type that inherits from the class), and you can't have a private virtual (it makes no sense). You could perhaps override an internal virtual, but I suspect even this may hit security issues. So ultimately, I'd say no.

Marc Gravell
+4  A: 

Not by using Reflection alone. Perhaps the best you could do is to use Reflection, combined with Reflection.Emit or the CodeDom to duplicate the class into a new namespace. When you come across the private method you want to replace, you don't copy it, you emit your replacement.

However, there are many techniques a developer can use that make this technique much, much harder. Breaking the implementation of the class into many private or internal classes is one such.

Note: using the CodeDom you'd have to build the graph in memory, compile it, and then load the resulting assembly.

This is probably a LOT more trouble than it is worth.

The other way to do it would be to use Reflector to disassemble the class, take the code and build your own class from it with the method replace. Again there are significant technical and legal hurdles to overcome. You may learn a lot from the disassembled code though.

Oplopanax
...or you may learn nothing, if the code is obfuscated.
Anton Tykhyy
of you could learn that some code is obfuscated :-)
Oplopanax
+1  A: 

Typemock Isolator is supposed to be able to do this, but does so through the .NET profiler APIs (according to Roy Osherove in The Art of Unit Testing).

TrueWill