Type Reflection
In the .NET universe, reflection is the process of runtime type discovery.
Using reflection services, you are able to programmatically obtain the same metadata information displayed by ildasm.exe using a friendly object model.
For example, through reflection, you can obtain a list of all types contained within a given .dll or .exe assembly, including the methods, fields, properties, and events defined by a given type.
Core items of reflection
Type | Meaning in Life |
Assembly | This abstract class contains a number of static methods that allow you to load, investigate, and manipulate an assembly. |
AssemblyName | This class allows you to discover numerous details behind an assembly’s identity (version information, culture information, and so forth). |
EventInfo | This abstract class holds information for a given event. |
FieldInfo | This abstract class holds information for a given field. |
MemberInfo | This is the abstract base class that defines common behaviors for the |
MethodInfo | This abstract class contains information for a given method. |
Module | This abstract class allows you to access a given module within a multifile assembly. |
ParameterInfo | This class holds information for a given parameter. |
PropertyInfo | This abstract class holds information for a given property. |
The System.Type
Class
System.Type
ClassThe System.Type
class defines a number of members that can be used to examine a type’s metadata, a great number of which return types from the System.Reflection
namespace. For example, Type.GetMethods()
returns an array of MethodInfo
objects.
Type | Meaning in Life |
IsAbstract IsArray IsClass IsCOMObject IsEnum IsGenericTypeDefinition IsGenericParameter IsInterface IsPrimitive IsNestedPrivate IsNestedPublic IsSealed IsValueType | These properties (among others) allow you to discover a number of basic traits about the Type you are referring to (e.g., if it is an abstract entity, an array, a nested class, and so forth). |
GetConstructors() GetEvents() GetFields() GetInterfaces() GetMembers() GetMethods() GetNestedTypes() GetProperties() | These methods (among others) allow you to obtain an array representing the items (interface, method, property, etc.) you are interested in. Each method returns a related array. |
FindMembers() | This method returns a |
GetType() | This static method returns a |
InvokeMember() | This method allows “late binding” for a given item. |
GetType() vs typeof(T)
You cannot do is directly create a Type
object using the new keyword, as Type
is an abstract class.
System.Object
defines a method named GetType()
, which returns an instance of the Type
class that represents the metadata for the current object.
The next way to obtain type information is using the C# typeof
operator, like so:
Unlike System.Object.GetType()
, the typeof
operator is compile-time and it does not need to first create an object instance to extract type information.
Last updated