What is the property of the C# language that makes reflection possible? Is it something that all object oriented language can do or is it something that all interpreted language can do? Or something else...
A compiler knows a lot about the program you write. It knows every class you programmed, the names of the methods, the arguments they take. Traditionally, compilers threw that extra info about your program away after they generated the executable code for your program.
Not a .NET compiler, it preserves that info. It is stored in the metadata of an assembly. An extra data structure in a .NET .exe or .dll file, beyond the generated code. With plumbing in the runtime support library to read that data structure at runtime, the System.Type class is instrumental.
That's not where it ends, you can also add arbitrary extra data to that metadata. Which is what an [attribute] is all about.
This enables all kinds of very interesting and useful features. Like dynamically altering the way code gets generated at runtime. Or dynamically creating objects without knowing their class names. Or converting the view of a type from its implementation to a useful other representation that's easier to handle. Which in turn enables features like serialization and design-time support. Reflection is the engine behind this, metadata is the source.
Metadata of all types/methods in C# can be accessed by reflection. Usually you have to use BindingFlags to specify types of objects you need.
Example:
MethodInfo[] myArrayMethodInfo1 = myType.GetMethods(BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.DeclaredOnly);
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