After seeing this: Do access modifiers affect reflection also?
I tried using this, but it doesn\'t work:
Though I absolutely agree with the idea of access modifiers not being a security feature, just for the sake of programming I've been thinking a bit about this, and I've got a simple, not much useful mechanism, fight Reflection with Reflection :-)
Be advised, it's just a silly proof of concept, I'm not taking into account Generic methods, it would need changes for that...
The idea is, at the start of every private method that you want to secure from being "illegally" invoked, you just check via Reflection that you're being invoked from another method in that class, not from outside. So you would use: new StackTrace().GetFrame(1).GetMethod(); to get the MethodBase of your invoker and would compare it against the list of MethodInfos for your class.
You can add it to a helper class (anyway you'll need a IEqualityComparer to compare MethodBases...
One problem is that you would also be preventing some correct invocations, like invoking it through a delegate or through Reflection from another of your methods... so you should be careful with when you use it.
You can my implementation here
If someone can currently use reflection on your private methods, then they already have enough access to sidestep anything else you place in their way. Running with less trust may be an option, but that is only to prevent things like plugins from having too much access - it won't stop a user with (say) admin access to the box, who can simply elevate the access.
If you don't want code running, don't put it in physical reach of the malicious user; keep it at a web-service or similar. Any code available to a user can be used directly, or indirectly by decompiling it (and deobfuscating it if needed). You can use some tricks to get in their way (checking the caller via the stacktrace etc), but that will not stop someone determined.
Access modifiers are not a security mechanism.
If if you could prevent your function from being called via reflection, the user can just decompile your program, extract that function, put it in a new assembly and execute it.