CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
Obtaining a Type Reference Using typeof()
The next way to obtain type information is using the C# typeof operator, like so:
// Get the type using typeof.
Type t = typeof(SportsCar);
Unlike System.Object.GetType(), the typeof operator is helpful in that you do not need to first
create an object instance to extract type information. However, your code base must still have compiletime knowledge of the type you are interested in examining, as typeof expects the strongly typed name
of the type.
Obtaining a Type Reference Using System.Type.GetType()
To obtain type information in a more flexible manner, you may call the static GetType() member of the
System.Type class and specify the fully qualified string name of the type you are interested in examining.
Using this approach, you do not need to have compile-time knowledge of the type you are extracting
metadata from, given that Type.GetType() takes an instance of the omnipresent System.String.
Note When I say you do not need compile-time knowledge when calling Type.GetType(), I am referring to the
fact that this method can take any string value whatsoever (rather than a strongly typed variable). Of course, you
would still need to know the name of the type in a “stringified” format!
The Type.GetType() method has been overloaded to allow you to specify two Boolean parameters,
one of which controls whether an exception should be thrown if the type cannot be found, and the other
of which establishes the case sensitivity of the string. To illustrate, ponder the following:
// Obtain type information using the static Type.GetType() method
// (don't throw an exception if SportsCar cannot be found and ignore case).
Type t = Type.GetType("CarLibrary.SportsCar", false, true);
In the previous example, notice that the string you are passing into GetType() makes no mention of
the assembly containing the type. In this case, the assumption is that the type is defined within the
currently executing assembly. However, when you wish to obtain metadata for a type within an external
private assembly, the string parameter is formatted using the type’s fully qualified name, followed by a
comma, followed by the friendly name of the assembly containing the type, like so:
// Obtain type information for a type within an external assembly.
Type t = Type.GetType("CarLibrary.SportsCar, CarLibrary");
As well, do know that the string passed into Type.GetType() may specify a plus token (+) to denote a
nested type. Assume you wish to obtain type information for an enumeration (SpyOptions) nested within
a class named JamesBondCar. To do so, you would write the following:
// Obtain type informat