Reflection

The right Type

The Type class is the foundation of Reflection. It serves as runtime information about an assembly, a module or a type. Fortunately, obtaining a reference to the Type of an object is very simply, since every class that inherits from the Object class, has a GetType() method. If you need information about a non-instantiated type, you may use the globally available typeof() method, which will do just that. Consider the following examples, where we use both approaches:

We use the GetType() method on our own variable, and then we use the typeof() on a known class, the Int32. As you can see, the result in both cases is a Type object, for which we can read the FullName property.

At some point, you might even only have the name of the type that you're looking for. In that case, you will have to get a reference to it from the proper assembly. In the next example, we get a reference to the executing assembly, that is, the assembly from where the current code is being executed from, and then we list all of it's types:

The output will be the name of the two declared classes, Program and DummyClass, but in a more complex application, the list would probably be more interesting. In this case, we only get the name of the type, but obviously we would be able to do a lot more, with the Type reference that we get. In the next chapters, I will show you a bit more on what we can do with it.