Reflection In .NET

Introduction

In this article, I will cover the basics of .NET Reflection with examples. I have stated with definition of .NET Reflection and its roadmap. We'll see a list of the 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. The use of properties and methods of Type class in .NET Reflection with examples are interesting in this article. You will also see advanced Reflection topics like dynamically loading an assembly and late binding at 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 the application to collect information about itself and also manipulate 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 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.

class view

Roadmap

The System.Reflection namespace and System. Type class plays an important role in .NET Reflection. These two work together and allow you to reflect on many other aspects of a type.

System reflection

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 the .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 several 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 a dynamic set and 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.

To continue with all the examples given in this article, I am using the 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 variables
        public string Color;
        // private variables
        // String licensePlate; // e.g. "Californi 111 222"
        // double maxSpeed; // in kilometers per hour
        // int startMiles; // Stating odometer reading
        // int endMiles; // Ending odometer reading
        // double gallons; // Gallons of gas used between the readings
        // private variables
        private int _speed;
        // Speed - read-only property to return the speed
        public int Speed
        {
            get { return _speed; }
        }
        // Accelerate - add mph to the speed
        public void Accelerate(int accelerateBy)
        {
            // Adjust the speed
            _speed += accelerateBy;
        }
        // IsMoving - is the car moving?
        public bool IsMoving()
        {
            // Is the car's speed zero?
            if (Speed == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        // Constructor
        public Car()
        {
            // Set the default values
            Color = "White";
            _speed = 0;
        }
        // Overloaded constructor
        public Car(string color, int speed)
        {
            Color = color;
            _speed = speed;
        }
        // Methods
        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
    {
        // Constructor
        public SportsCar()
        {
            // Change the default values
            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.

Obtaining type information

Using System.Object.GetType()

This method returns a Type object that represents the type of an object. 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 the 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:

  1. fully qualified string name of the type you are interested in examining
  2. exception should be thrown if the type cannot be found
  3. establishes the case sensitivity of the string

TypeGetTypeDemo.cs

using System;
namespace Reflection
{
    class TypeGetTypeDemo
    {
        static void Main(string[] args)
        {
            // Obtain type information using the static Type.GetType() method.
            // (don't throw an exception if Car cannot be found and ignore case).
            Type t = Type.GetType("Reflection.Car", false, true);
            Console.WriteLine(t.FullName);
            Console.ReadLine();
        }
    }
}

Output

Reflection.Car

Using type () C# operator

The final way to obtain a type of information is using the C# type 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)
        {
            // Get the Type using typeof.
            Type t = typeof(Car);
            Console.WriteLine(t.FullName);
            Console.ReadLine();
        }
    }
}

Output

Reflection.Car

Type properties

The System. Type class defines several members that can be used to examine a type's metadata. You can split these properties into three categories.

  1. Several properties retrieve the strings containing various names associated with the class, as shown in the following table:
  2. It is also possible to retrieve references to further type objects that represent related classes, as shown in the following table:
  3. Several Boolean properties indicate whether this type is, for example, a class, an enum, and so on.

Here is an 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()
        {
            // Modify this line to retrieve details of any other data type
            // Get name of type
            Type t = typeof(Car);
            GetTypeProperties(t);
            Console.ReadLine();
        }
        public static void GetTypeProperties(Type t)
        {
            StringBuilder OutputText = new StringBuilder();
            // Properties retrieve the strings
            OutputText.AppendLine("Analysis of type " + t.Name);
            OutputText.AppendLine("Type Name: " + t.Name);
            OutputText.AppendLine("Full Name: " + t.FullName);
            OutputText.AppendLine("Namespace: " + t.Namespace);
            // Properties retrieve references
            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("UnderlyingSystem Type Assembly: " + tUnderlyingSystem.Assembly);
            }
            // Properties retrieve boolean
            OutputText.AppendLine("Is Abstract Class: " + t.IsAbstract);
            OutputText.AppendLine("Is an Array: " + 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 the System.Types 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)
{
    // etc.
}

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.

Namespace hierarchy

For example, the simplest overload of GetMethods() takes no parameters.

GetMethodsDemo.cs

using System;
using System.Reflection;
namespace Reflection
{
    class GetMethodsDemo
    {
        static void Main()
        {
            // Get name of type
            Type t = typeof(Car);
            GetMethod(t);
            GetMethods(t);
            Console.ReadLine();
        }
        // Display method names of type.
        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("");
        }
        // Display method name of type.
        public static void GetMethod(Type t)
        {
            Console.WriteLine("***** Method *****");
            // This searches for name is case-sensitive.
            // The search includes public static and public instance methods.
            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. 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 an object from being obtained. For example, try substituting this call to GetMethods( ) into the preceding program.

// Now, only methods declared by MyClass are obtained.
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 the 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()
        {
            // Get name of type
            Type t = typeof(Car);
            GetFields(t);
            GetProperties(t);
            Console.ReadLine();
        }
        // Display field names of type.
        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("");
        }
        // Display property names of type.
        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()
        {
            // Get name of type
            Type t = typeof(Car);
            GetInterfaces(t);
            Console.ReadLine();
        }
        // Display implemented interfaces.
        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 a MethodInfo[] array using the 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()
        {
            // Get name of type
            Type t = typeof(Car);
            GetParametersInfo(t);

            Console.ReadLine();
        }
        // Display Method return Type and parameters list
        public static void GetParametersInfo(Type t)
        {
            Console.WriteLine("***** GetParametersInfo *****");
            MethodInfo[] mi = t.GetMethods();
            foreach (MethodInfo m in mi)
            {
                // Get return value.
                string retVal = m.ReturnType.FullName;
                StringBuilder paramInfo = new StringBuilder();
                paramInfo.Append("(");
                // Get parameters.
                foreach (ParameterInfo pi in m.GetParameters())
                {
                    paramInfo.Append(string.Format("{0} {1} ", pi.ParameterType, pi.Name));
                }
                paramInfo.Append(")");
                // Now display the basic method sig.
                Console.WriteLine("->{0} {1} {2}", retVal, m.Name, paramInfo);
            }
            Console.WriteLine("");
        }
    }
}

Output

***** GetParametersInfo *****

System.Int32 get_Speed ()

System.Void Accelerate (System.Int32 accelerate )

System.Boolean IsMoving ()

System.Double calculateMPG (System.Int32 startMiles System.Int32 endmills 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 GetConstructorInfoDemo
    {
        static void Main()
        {
            // Get name of type
            Type t = typeof(Car);
            GetConstructorsInfo(t);

            Console.ReadLine();
        }
        // Display method names of type.
        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 provides 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 instances of types returned by the Assembly class

Dynamically loading an Assembly

Assembly Class provides the following methods to load an assembly at runtime,

  1. Load (): This static overloaded method takes the assembly name as an input parameter and searches the given assembly name in the system.
  2. LoadFrom (): This static overloaded method takes the complete path of the assembly, it will directly look into that particular location instead of searching in the system.
  3. GetExecutingAssembly (): The Assembly class also provides another method to obtain the currently running assembly information using the GetExecutingAssembly() methods. This method is not overloaded.
  4. GetTypes(): The assembly class also provides a nice feature called the GetTypes Method which allows you to obtain details of all the types that are defined in the corresponding assembly.
  5. 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

using System;
using System.Reflection;
class AssemblyDemo
{
    static void Main()
    {
        Assembly objAssembly; 
        // You must supply a valid fully qualified assembly name here.
        objAssembly = Assembly.Load("mscorlib,2.0.0.0,Neutral,b77a5c561934e089");
        // Loads an assembly using its file name
        // objAssembly = Assembly.LoadFrom(@"C:\Windows\Microsoft.NET\Framework\v1.1.4322\caspol.exe");
        // Loads the currently running process assembly
        // objAssembly = Assembly.GetExecutingAssembly();
        Type[] Types = objAssembly.GetTypes(); 
        // Display all the types contained in the specified assembly.
        foreach (Type objType in Types)
        {
            Console.WriteLine(objType.Name.ToString());
        }
        // Fetching custom attributes within an assembly
        Attribute[] arrayAttributes = Attribute.GetCustomAttributes(objAssembly);
        // assembly1 is an Assembly object
        foreach (Attribute attrib in arrayAttributes)
        {
            Console.WriteLine(attrib.TypeId);
        }
        Console.ReadLine();
    }
}

Exception instance

Late Binding

Late binding is a 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 do 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 make 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;
            // Loads the current executing assembly
            objAssembly = Assembly.GetExecutingAssembly();
            // Get the class type information in which late binding is applied
            Type classType = objAssembly.GetType("Reflection.Car");
            // Create an instance of the class using System.Activator class
            object obj = Activator.CreateInstance(classType);
            // Get the method information
            MethodInfo mi = classType.GetMethod("IsMoving");
            // Late Binding using Invoke method without parameters
            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");
            }
            // Late Binding with parameters
            object[] parameters = new object[3];
            parameters[0] = 32456;   // Parameter 1: startMiles
            parameters[1] = 32810;   // Parameter 2: endMiles
            parameters[2] = 10.6;    // Parameter 3: gallons
            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 cover most of the important functionality related to .NET reflection.

Thanks for reading my article; I hope you enjoyed it.


Similar Articles