Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Did Microsoft meant to support Reflection in .Net? or was it obligated to?

As the title states, was reflection in .Net a target or was it a natural result from the design of .Net internals (like the way languages compiled into an IL assemblies)?

And about the gain of reflection. Here's some uses of reflection which I see here in this website:

  • Using reflection to access an overridden base class' method.
  • Using reflection to access a private field of a class.

and my other question is if we were able to access private fields and overridden base methods (to break the core framework rules) by using reflection then why to bother putting those (strict?) roles in the first place?

like image 715
Ken D Avatar asked Feb 26 '23 15:02

Ken D


1 Answers

Reflection is a very powerful tool; I fully expect that was very, very deliberate. I don't have a quote to support that, though; however - yes, a strong reflection API is also necessary for things like BinaryFormatter and the "remoting" stack that was in from day-0 (but which is less popular now).

In fact, a vast amount of library code uses reflection; data binding or serialization, for example. Without reflection you would need to write lots of code manually in order to do some very simple things that the libraries handle automatically via reflection.

Another big use is meta-programming; writing code at runtime to augment the compiled code; useful in things like IoC / DI, etc. Or just when you need reflection but faster ;p

Re things like private; there are trust levels in .NET; not all code can access your internals, unless you run at full trust (admittedly, most code does run at full trust). And beyond a certain level of paranoia it is a false aim anyway, as there are ways external to .NET of poking into a process.

like image 60
Marc Gravell Avatar answered Feb 28 '23 17:02

Marc Gravell