Why can reflection access protected/private member of class in C#?
Is this not safe for the class, why is reflection given such power? Is this an anti-pattern?
Member accessibility is not a security feature. It is there to protect the programmer against himself or herself. It helps implementing encapsulation but it is by no means a security feature.
Reflection is tedious enough to use so that people normally don't go out of their way to use it to access non-public members. It's also quite slow. Reflection is normally used in special cases only. However, nothing can protect completely against human stupidity, if someone wants to abuse reflection he can easily do it, but even without the reflection API, they can achieve the same thing (if they're running in full trust, that is) if they are determined enough.
This is necessary for scenarios such as remoting, serialization, materialization, etc. You shouldn't use it blindly, but note that these facilities have always been available in any system (essentially, by addressing the memory directly). Reflection simply formalises it, and places controls and checks in the way - which you aren't seeing because you are presumably running at "full trust", so you are already stronger than the system that is being protected.
If you try this in partial trust, you'll see much more control over the internal state.
Is it an anti-pattern?
Only if your code uses it inappropriately. For example, consider the following (valid for a WCF data-contract):
[DataMember]
private int foo;
public int Foo { get {return foo;} set {foo = value;} }
Is it incorrect for WCF to support this? I suspect not... there are multiple scenarios where you want to serialize something that isn't part of the public API, without having a separate DTO. Likewise, LINQ-to-SQL will materialize into private members if you so elect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With