4

We can use reflection to get or set value of any private member in C# class. (using BindingFlags.NonPublic etc.)

If this is the case, how come private member is really private? How can we be assured that the things which are purposely stored in the private fields remain private in true sense?

Learner
  • 4,661
  • 9
  • 56
  • 102
  • 4
    You can't really prevent this - reflection is a backdoor into the implementation of your class. – StuartLC Oct 21 '13 at 09:04
  • 3
    In reality, you can't; Making an implementation `private` `internal`, etc is about specifying intent in the design and how components are intended to be used. – Russ Cam Oct 21 '13 at 09:06
  • 2
    This question was asked a number of times. This one has great answers: http://stackoverflow.com/q/2084353/694852. And this one was havily upvoted: http://stackoverflow.com/q/16942114/694852. – Artemix Oct 21 '13 at 09:12
  • 1
    http://msdn.microsoft.com/en-us/library/stfy7tfc.aspx – Hans Passant Oct 21 '13 at 09:33

1 Answers1

2

You cannot. Access modifiers are there to provide encapsulation for object orientated programming, not for runtime security.

If you need security, you will need to use higher level features.

Community
  • 1
  • 1
Gusdor
  • 14,001
  • 2
  • 52
  • 64