Introduction
In this article, I will cover basics of .NET Reflection with examples. I have stated with definition of .NET Reflection and its roadmap. We'll see list of most used classes in the System.Reflection namespace that defines most of the .NET Reflection related functionality. You will also learn how to get the type information using different ways. Use of properties and methods of Type class in .NET Reflection with examples are interesting in this article. You will also see advance Reflection topic like dynamically loading an assembly and late binding in the end of this article.
What is .NET Reflection?
.NET Framework's Reflection API allows you to fetch Type (Assembly) information at runtime or programmatically. We can also implement late binding using .NET Reflection. At runtime, Reflection uses the PE file to read the metadata about an assembly. Reflection enables you to use code that was not available at compile time. .NET Reflection allows application to collect information about itself and also manipulate on itself. It can be used effectively to find all the types in an assembly and/or dynamically invoke methods in an assembly. This includes information about the type, properties, methods and events of an object. With reflection, we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. We can also access attributes using Reflection. In short, Reflection can be very useful if you don't know much about an assembly.
Using reflection, you can get the kind of information that you will see in the Class Viewer, Object Explorer, or a Class Explorer. You can see all the types in an assembly, their members, their types, and metadata. Here is an example of the Class View in Visual Studio.
Roadmap
The System.Reflection namespace and System.Type class play an important role in .NET Reflection. These two works together and allow you to reflect over many other aspects of a type.
System.Reflection Namespace
System.Reflection Namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types; this process is known as Reflection in .NET framework. The following table describes some of the commonly used classes:
Class |
Description |
Assembly |
Represents an assembly, which is a reusable, versionable, and self-describing building block of a common language runtime application. This class contains a number of methods that allow you to load, investigate, and manipulate an assembly. |
Module |
Performs reflection on a module. This class allows you to access a given module within a multifile assembly. |
AssemblyName |
This class allows you to discover numerous details behind an assembly's identity. An assembly's identity consists of the following: • Simple name. • Version number. • Cryptographic key pair. • Supported culture |
EventInfo |
This class holds information for a given event. Use the EventInfo class to inspect events and to bind to event handlers FieldInfo This class holds information for a given field.
Fields are variables defined in the class. FieldInfo provides access to the metadata for a field within a class and provides dynamic set and get functionality for the field. The class is not loaded into memory until invoke or get is called on the object. |
MemberInfo |
The MemberInfo class is the abstract base class for classes used to obtain information about all members of a class (constructors, events, fields, methods, and properties). |
MethodInfo |
This class contains information for a given method. |
ParameterInfo |
This class holds information for a given parameter. |
PropertyInfo |
This class holds information for a given property. |
Before we start using Reflection, it is also necessary to understand the System.Type class.
In order to continue with all the examples given in this article, I am using Car class as an example, it will look like this:
ICar.cs - Interface
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace Reflection
- {
- interface ICar
- {
- bool IsMoving();
- }
- }
Car.cs - Class
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace Reflection
- {
- internal class Car
- {
-
- public string Color;
-
-
-
-
-
-
-
-
-
- private int _speed;
-
-
- public int Speed
- {
- get { return _speed; }
- }
-
-
- public void Accelerate(int accelerateBy)
- {
-
- _speed += accelerateBy;
- }
-
-
- public bool IsMoving()
- {
-
- if (Speed == 0)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
-
-
- public Car()
- {
-
- Color = "White";
- _speed = 0;
- }
-
-
- public Car(string color, int speed)
- {
- Color = color;
- _speed = speed;
- }
-
- public double calculateMPG(int startMiles, int endMiles, double gallons)
- {
- return (endMiles - startMiles) / gallons;
- }
- }
- }
SportsCar.cs - Class
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace Reflection
- {
- internal class SportsCar : Car
- {
-
- public SportsCar()
- {
-
- Color = "Green";
- }
- }
- }
The System.Type Class
The System.Type class is the main class for the .NET Reflection functionality to access metadata. The System.Type class is an abstract class and represents a type in the Common Type System (CLS). It represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.
The Type class and its members are used to get information about a type declaration and its members such as constructors, methods, fields, properties, and events of a class, as well as the module and the assembly in which the class is deployed.
There are three ways to obtain a Type reference.
Using System.Object.GetType()
This method returns a Type object that represents the type of an object. Obviously, this approach will only work if you have the compile-time knowledge of the type.
ObjectGetTypeDemo.cs
- using System;
- namespace Reflection
- {
- class ObjectGetTypeDemo
- {
- static void Main(string[] args)
- {
- Car c = new Car();
- Type t = c.GetType();
- Console.WriteLine(t.FullName);
- Console.ReadLine();
- }
- }
- }
Output
Reflection.Car
Using System.Type.GetType()
Another way of getting Type information, which is more flexible is using the GetType() static method of Type class. This method gets the type with the specified name, performing a case-sensitive search.
The Type.GetType() is an overloaded method and accepts the following parameters:
- fully qualified string name of the type you are interested in examining
- exception should be thrown if the type cannot be found
- establishes the case sensitivity of the string
TypeGetTypeDemo.cs
- using System;
- namespace Reflection
- {
- class TypeGetTypeDemo
- {
- static void Main(string[] args)
- {
-
-
- Type t = Type.GetType("Reflection.Car", false, true);
- Console.WriteLine(t.FullName);
- Console.ReadLine();
- }
- }
- }
Output
Reflection.Car
Using typeof () C# operator
The final way to obtain a type information is using the C# typeof operator. This operator takes the name of the type as a parameter.
TypeofDemo.cs
- using System;
- namespace Reflection
- {
- class TypeofDemo
- {
- static void Main(string[] args)
- {
-
- Type t = typeof(Car);
- Console.WriteLine(t.FullName);
- Console.ReadLine();
- }
- }
- }
Output
Reflection.Car
Type Properties
The System.Type class defines a number of members that can be used to examine a type's metadata. You can split these properties into three categories,
- A number of properties retrieve the strings containing various names associated with the class, as shown in the following table:
Property |
Returns |
Name |
The name of the data type |
FullName |
The fully qualified name of the data type (including the namespace name) |
Namespace |
The name of the namespace in which the data type is defined |
- It is also possible to retrieve references to further type objects that represent related classes, as shown in the following table:
Property |
Returns Type Reference Corresponding To |
BaseType |
Immediate base type of this type |
UnderlyingSystemType |
The type that this type maps to in the .NET runtime (recall that certain .NET base types actually map to specific predefined types recognized by IL) |
- A number of Boolean properties indicate whether this type is, for example, a class, an enum, and so on.
Type |
Meaning in Life |
IsAbstract IsArray IsClass IsCOMObject IsEnum IsGenericTypeDefinition IsGenericParameter IsInterface IsPrimitive IsPublic IsNestedPrivate IsNestedPublic IsSealed IsValueType IsPointer |
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 method, an array, a nested class, and so forth) |
Here is the example of displaying type information using System.Type class properties:
TypePropertiesDemo.cs
- using System;
- using System.Text;
- using System.Reflection;
- namespace Reflection
- {
- class TypePropertiesDemo
- {
- static void Main()
- {
-
-
- Type t = typeof(Car);
- GetTypeProperties(t);
- Console.ReadLine();
- }
- public static void GetTypeProperties(Type t)
- {
- StringBuilder OutputText = new StringBuilder();
-
-
- OutputText.AppendLine("Analysis of type " + t.Name);
- OutputText.AppendLine("Type Name: " + t.Name);
- OutputText.AppendLine("Full Name: " + t.FullName);
- OutputText.AppendLine("Namespace: " + t.Namespace);
-
-
- Type tBase = t.BaseType;
-
- if (tBase != null)
- {
- OutputText.AppendLine("Base Type: " + tBase.Name);
- }
- Type tUnderlyingSystem = t.UnderlyingSystemType;
- if (tUnderlyingSystem != null)
- {
- OutputText.AppendLine("UnderlyingSystem Type: " + tUnderlyingSystem.Name);
-
- }
-
- OutputText.AppendLine("Is Abstract Class: " + t.IsAbstract);
- OutputText.AppendLine("Is an Arry: " + t.IsArray);
- OutputText.AppendLine("Is a Class: " + t.IsClass);
- OutputText.AppendLine("Is a COM Object : " + t.IsCOMObject);
-
- OutputText.AppendLine("\nPUBLIC MEMBERS:");
- MemberInfo[] Members = t.GetMembers();
-
- foreach (MemberInfo NextMember in Members)
- {
- OutputText.AppendLine(NextMember.DeclaringType + " " +
- NextMember.MemberType + " " + NextMember.Name);
- }
- Console.WriteLine(OutputText);
- }
- }
- }
Output
Analysis of type Car
Type Name: Car
Full Name: Reflection.Car
Namespace: Reflection
Base Type: Object
UnderlyingSystem Type: Car
Is Abstract Class: False
Is an Arry: False
Is a Class: True
Is a COM Object : False
PUBLIC MEMBERS:
Reflection.Car Method get_Speed
Reflection.Car Method Accelerate
Reflection.Car Method IsMoving
Reflection.Car Method calculateMPG
System.Object Method ToString
System.Object Method Equals
System.Object Method GetHashCode
System.Object Method GetType
Reflection.Car Constructor .ctor
Reflection.Car Constructor .ctor
Reflection.Car Property Speed
Reflection.Car Field Color
Type Methods
Most of the methods of System.Type are used to obtain details of the members of the corresponding data type - constructors, properties, methods, events, and so on. There is a long list of methods exist, but they all follow the same pattern.
Returned Type |
Methods (The Method with the Plural Name Returns an Array) |
Description |
ConstructorInfo |
GetConstructor(), GetConstructors() |
These methods allow you to obtain an array representing the items (interface, method, property, etc.) you are interested in. Each method returns a related array (e.g., GetFields() returns a FieldInfo array, GetMethods() returns a MethodInfo array, etc.). Be aware that each of these methods has a singular form (e.g., GetMethod(), GetProperty(), etc.) that allows you to retrieve a specific item by name, rather than an array of all related items. |
EventInfo |
GetEvent(), GetEvents() |
FieldInfo |
GetField(), GetFields() |
InterfaceInfo |
GetInterface(), GetInterfaces() |
MemberInfo |
GetMember(), GetMembers() |
MethodInfo |
GetMethod(), GetMethods() |
PropertyInfo |
GetProperty(), GetProperties() |
|
FindMembers() |
This method returns an array of MemberInfo types based on search criteria. |
Type |
GetType() |
This static method returns a Type instance given a string name. |
|
InvokeMember() |
This method allows late binding to a given item. |
For example, two methods retrieve details of the methods of the data type: GetMethod() and GetMethods().
- Type t = typeof(Car);
- MethodInfo[] methods = t.GetMethods();
- foreach (MethodInfo nextMethod in methods)
- {
-
- }
Reflecting on Methods
GetMethod() returns a reference to a System.Reflection.MethodInfo object, which contains details of a method. Searches for the public method with the specified name.
GetMethods() returns an array of such references. The difference is that GetMethods() returns details of all the methods, whereas GetMethod() returns details of just one method with a specified parameter list.
Both methods have overloads that take an extra parameter, a BindingFlags enumerated value that indicates which members should be returned - for example, whether to return public members, instance members, static members, and so on.
MethodInfo is derived from the abstract class MethodBase, which inherits MemberInfo. Thus, the properties and methods defined by all three of these classes are available for your use.
For example, the simplest overload of GetMethods() takes no parameters.
GetMethodsDemo.cs
- using System;
- using System.Reflection;
-
- namespace Reflection
- {
- class GetMethodsDemo
- {
- static void Main()
- {
-
- Type t = typeof(Car);
- GetMethod(t);
- GetMethods(t);
-
- Console.ReadLine();
- }
-
- public static void GetMethods(Type t)
- {
- Console.WriteLine("***** Methods *****");
- MethodInfo[] mi = t.GetMethods();
- foreach (MethodInfo m in mi)
- Console.WriteLine("->{0}", m.Name);
- Console.WriteLine("");
- }
-
- public static void GetMethod(Type t)
- {
- Console.WriteLine("***** Method *****");
-
-
- MethodInfo mi = t.GetMethod("IsMoving");
- Console.WriteLine("->{0}", mi.Name);
- Console.WriteLine("");
- }
- }
- }
Output
***** Method *****
->IsMoving
***** Methods *****
->get_Speed
->Accelerate
->IsMoving
->calculateMPG
->ToString
->Equals
->GetHashCode
->GetType
Here, you are simply printing the name of the method using the MethodInfo.Name property. As you might guess, MethodInfo has many additional members that allow you to determine if the method is static, virtual, or abstract. As well, the MethodInfo type allows you to obtain the method's return value and parameter set.
A Second Form of GetMethods( )
A second form of GetMethods( ) lets you specify various flags that filter the methods that are retrieved. It has this general form:
MethodInfo[ ] GetMethods(BindingFlags flags)
This version obtains only those methods that match the criteria that you specify. BindingFlags is an enumeration. Here are several commonly used values:
Value |
Meaning |
DeclaredOnly |
Retrieves only those methods defined by the specified class. Inherited methods are not included. |
Instance |
Retrieves instance methods. |
NonPublic |
Retrieves nonpublic methods. |
Public |
Retrieves public methods. |
Static |
Retrieves static methods. |
You can OR together two or more flags. In fact, minimally you must include either Instance or Static with Public or NonPublic. Failure to do so will result in no methods being retrieved.
One of the main uses of the BindingFlags form of GetMethods( ) is to enable you to obtain a list of the methods defined by a class without retrieving the inherited methods. This is especially useful for preventing the methods defined by object from being obtained. For example, try substituting this call to GetMethods( ) into the preceding program:
-
- MethodInfo[] mi = t.GetMethods(BindingFlags.DeclaredOnly |
- BindingFlags.Instance |BindingFlags.Public);
Reflecting on Fields and Properties
Behavior of the Type.GetField() and Type.GetFields() is exactly similar to above two methods except Type.GetField() returns to references of System.Reflection.MethodInfo and Type.GetFields() returns to references of System.Reflection.MethodInfo array. Similarly Type.GetProperty() and Type.GetProperties() too.
The logic to display a type's properties is similar:
GetFieldsPropertiesDemo.cs
- using System;
- using System.Reflection;
-
- namespace Reflection
- {
- class GetFieldsPropertiesDemo
- {
- static void Main()
- {
-
- Type t = typeof(Car);
- GetFields(t);
- GetProperties(t);
-
- Console.ReadLine();
- }
-
-
- public static void GetFields(Type t)
- {
- Console.WriteLine("***** Fields *****");
- FieldInfo[] fi = t.GetFields();
- foreach (FieldInfo field in fi)
- Console.WriteLine("->{0}", field.Name);
- Console.WriteLine("");
- }
-
- public static void GetProperties(Type t)
- {
- Console.WriteLine("***** Properties *****");
- PropertyInfo[] pi = t.GetProperties();
- foreach (PropertyInfo prop in pi)
- Console.WriteLine("->{0}", prop.Name);
- Console.WriteLine("");
- }
- }
- }
Output
***** Fields *****
->Color
***** Properties *****
->Speed
Reflecting on Implemented Interfaces
GetInterfaces() returns an array of System.Types. his should make sense given that interfaces are, indeed, types:
GetInterfacesDemo.cs
- using System;
- using System.Reflection;
-
- namespace Reflection
- {
- class GetInterfacesDemo
- {
- static void Main()
- {
-
- Type t = typeof(Car);
- GetInterfaces(t);
-
- Console.ReadLine();
- }
-
- public static void GetInterfaces(Type t)
- {
- Console.WriteLine("***** Interfaces *****");
- Type[] ifaces = t.GetInterfaces();
- foreach (Type i in ifaces)
- Console.WriteLine("->{0}", i.Name);
- }
- }
- }
***** Interfaces *****
->ICar
Reflecting on Method Parameters and Return Values
To play with method parameters and their return types, we first need to build MethodInfo[] array using GetMethods() function. The MethodInfo type provides the ReturnType property and GetParameters() method for these very tasks.
- using System;
- using System.Reflection;
- using System.Text;
-
- namespace Reflection
- {
- class GetParameterInfoDemo
- {
- static void Main()
- {
-
- Type t = typeof(Car);
- GetParametersInfo(t);
-
- Console.ReadLine();
- }
-
- public static void GetParametersInfo(Type t)
- {
- Console.WriteLine("***** GetParametersInfo *****");
- MethodInfo[] mi = t.GetMethods();
- foreach (MethodInfo m in mi)
- {
-
- string retVal = m.ReturnType.FullName;
- StringBuilder paramInfo = new StringBuilder();
- paramInfo.Append("(");
-
-
- foreach (ParameterInfo pi in m.GetParameters())
- {
- paramInfo.Append(string.Format("{0} {1} ", pi.ParameterType, pi.Name));
- }
- paramInfo.Append(")");
-
-
- Console.WriteLine("->{0} {1} {2}", retVal, m.Name, paramInfo);
- }
- Console.WriteLine("");
- }
- }
- }
Output
***** GetParametersInfo *****
->System.Int32 get_Speed ()
->System.Void Accelerate (System.Int32 accelerateBy )
->System.Boolean IsMoving ()
->System.Double calculateMPG (System.Int32 startMiles System.Int32 endMiles Syst
em.Double gallons )
->System.String ToString ()
->System.Boolean Equals (System.Object obj )
->System.Int32 GetHashCode ()
->System.Type GetType ()
Reflecting on Constructor
GetConstractors() function returns an array of ConstractorInfo elements, which we can use to get constructors' information.
GetConstractorInfoDemo.cs
- using System;
- using System.Reflection;
- namespace Reflection
- {
- class GetConstractorInfoDemo
- {
- static void Main()
- {
-
- Type t = typeof(Car);
- GetConstructorsInfo(t);
-
- Console.ReadLine();
- }
-
- public static void GetConstructorsInfo(Type t)
- {
- Console.WriteLine("***** ConstructorsInfo *****");
- ConstructorInfo[] ci = t.GetConstructors ();
- foreach (ConstructorInfo c in ci)
- Console.WriteLine(c.ToString () );
- Console.WriteLine("");
- }
- }
- }
Output
***** ConstructorsInfo *****
Void .ctor()
Void .ctor(System.String, Int32)
Assembly Class
System.Reflection namespace provide a class called Assembly. We can use this Assembly class to fetch the information about the assembly and manipulate it; this class allows us to load modules and assemblies at run time. Assembly class contacts with PE file to fetch the metadata information about the assembly at runtime. Once we load an assembly using this Assembly class, we can search the type information within the assembly. It is also possible to create instance of types return by the Assembly class
Dynamically loading an Assembly
Assembly Class provides following methods to load an assembly at runtime,
- Load ()
This static overloaded method takes the assembly name as input parameter and searched the given assembly name in the system.
- LoadFrom ()
This static overloaded method take complete path of the an assembly, it will directly look into that particular location instead of searching in the system.
- GetExecutingAssembly ()
Assembly class also provide another method to obtain the currently running assembly information using GetExecutingAssembly() methods. This method is not overloaded one.
- GetTypes()
Assembly class also provide a nice feature called GetTypes Method which allows you to obtain details of all the types that are defined in the corresponding assembly.
- GetCustomAttributes()
This static overloaded method gets the attributes attached to the assembly. You can also call GetCustomAttributes() specifying a second parameter, which is a Type object that indicates the attribute class in which you are interested.
AssemblyDemo.cs
- class AssemblyDemo
- {
- static void Main()
- {
- Assembly objAssembly;
-
- objAssembly = Assembly.Load("mscorlib,2.0.0.0,Neutral,b77a5c561934e089");
-
-
-
-
-
- Type[] Types = objAssembly.GetTypes();
-
- foreach (Type objType in Types)
- {
- Console.WriteLine(objType.Name.ToString());
- }
-
-
- Attribute[] arrayAttributes =
- Attribute.GetCustomAttributes(objAssembly);
-
-
- foreach (Attribute attrib in arrayAttributes)
- {
- Console.WriteLine(attrib.TypeId);
- }
-
- Console.ReadLine();
- }
- }
Late Binding
Late binding is the powerful tool in .NET Reflection, which allows you to create an instance of a given type and invoke its members at runtime without having compile-time knowledge of its existence; this technique is also called dynamic invocation. This technique is useful when working with objects that are does not provide details at compile time. In this technique, developers are responsible for passing the correct signature of methods before invoking them, otherwise it will throw an error. It is very important to take the right decision when using this approach. Use of late binding may also impact the performance of your application.
LateBindingDemo.cs
- using System;
- using System.Reflection;
-
- namespace Reflection
- {
- class LateBindingDemo
- {
- static void Main()
- {
- Assembly objAssembly;
-
- objAssembly = Assembly.GetExecutingAssembly();
-
-
- Type classType = objAssembly.GetType("Reflection.Car");
-
-
- object obj = Activator.CreateInstance(classType);
-
-
- MethodInfo mi = classType.GetMethod("IsMoving");
-
-
- bool isCarMoving;
- isCarMoving = (bool)mi.Invoke(obj, null);
- if (isCarMoving)
- {
- Console.WriteLine("Car Moving Status is : Moving");
- }
- else
- {
- Console.WriteLine("Car Moving Status is : Not Moving");
- }
-
-
- object[] parameters = new object[3];
- parameters[0] = 32456;
- parameters[1] = 32810;
- parameters[2] = 10.6;
- mi = classType.GetMethod("calculateMPG");
- double MilesPerGallon;
- MilesPerGallon = (double)mi.Invoke(obj, parameters);
- Console.WriteLine("Miles per gallon is : " + MilesPerGallon);
-
- Console.ReadLine();
- }
-
- }
- }
Output
Car Moving Status is : Not Moving
Miles per gallon is : 33.3962264150943
Reflection Emit
Reflection emit supports the dynamic creation of new types at runtime. You can define an assembly to run dynamically or to save itself to disk, and you can define modules and new types with methods that you can then invoke.
Conclusion
Reflection in .NET is a big topic. In this article, I tried to covers most of the important functionality related to .NET reflection.
Thanks for reading my article; I hope you enjoyed it.