Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the property of the C# language that makes reflection possible?

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...

like image 835
Bastien Vandamme Avatar asked Dec 25 '22 14:12

Bastien Vandamme


2 Answers

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.

like image 105
Hans Passant Avatar answered May 10 '23 23:05

Hans Passant


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);
like image 34
semao Avatar answered May 10 '23 21:05

semao