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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
Only if your code uses it inappropriately. For example, consider the following (valid for a WCF data-contract):
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.