Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private methods using .NET reflection. Why?

I used reflection many times before on public methods, but I never realized that private methods can be invoked too. See Reflection with private members.

Why is that allowed in the first place? Isn't that going to break the rule of "private" being "private"?

like image 673
AJ. Avatar asked Feb 12 '26 16:02

AJ.


1 Answers

private in C# is truly only part of the language specification; in the C# language, as well as in the Visual Basic language or any other sensible .NET language (including CIL, what all the .NET languages compile to) one is prevented from accessing a private (or protected, if you're not within a derived class) member in the language. However, just because the language doesn't support publicly accessing private or protected members doesn't mean the underlying framework can't provide access to those members.

This is one of those cases where one typically shouldn't be using workarounds like reflection to access or modify private or protected members, but the framework allows one to anyway. Generally, you should have a very good reason to access private or protected members; one such reason, for example, is implementing a serializer that needs to look at the object's internal state to properly serialize the object. If you're not doing something like that, you should truly look at reimplementing the class you're poking around inside, so that you don't need to use reflection in your program.

like image 161
Adam Maras Avatar answered Feb 17 '26 12:02

Adam Maras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!