mardi 23 novembre 2021

Reflection, compile-time type, runtime type, assemblies, and how they fit together

I've been trying to piece together how reflection, compile-time type, runtime type, assemblies, and metadata fit together in C#. My understanding so far is that reflection allows the runtime to introspect upon the compiled code's assembly metadata. This metadata contains information about the methods and types in our program. For example, we get an object's type.

My questions are:

  1. When we're getting an object's type via reflection, are we getting the runtime type or static type?
  2. If we're able to get the runtime type from metadata, how is this happening?
  3. Couldn't I just use "GetType()"?
  4. And an assembly is compiled code, runtime types aren't known yet, so how can the runtime type be extracted from an assembly's metadata?

As an example:

Base b = new Derived();
Console.WriteLine(b.GetType());

I understand that Derived is logged. But how? If GetType retrieves the type via reflection, which consults the assembly's metadata, how is the runtime type being logged? Doesn't the metadata only contain type information based on compile time?

Just after some clarification, big or small, whatever is necessary. And please correct anything I've said that's incorrect.





Aucun commentaire:

Enregistrer un commentaire