Reflection in C# by oraclequest

   This article is aimed to explain reflection in .NET Framework.

 

Reflection is one of the features of .Net framework and has greater importance during the development of large applications. In brief it is a powerful way of collecting and manipulate information present in application’s assemblies and its metadata. Metadata contain all the Type information used by the application. The ability to obtain information at runtime also makes it even more advantageous. When reflection is used along with system.type, it allows the developer to get the valuable information about all the types and about the assemblies. We can even create the instances and then invoke various types that are used across the application.

 

What is Reflection?

 Reflection is the ability to find out information about objects, the application details (assemblies), its metadata at run-time.

  This 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 and to invoke the methods of object Invoke method can be used too. 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. If Attributes (C#) are used in application, then with help of reflection we can access these attributes. It can be even used to emit Intermediate Language code dynamically so that the generated code can be executed directly.

How to use Reflection in our applications?

System.Reflection namespace contains all the Reflection related classes. These classes are used to get information from any of the class under .NET framework. The Type class is the root of all reflection operations. Type is an abstract base class that acts as means to access metadata though the reflection classes. Using Type object, any information related to methods, implementation details and manipulating information can be obtained. The types include the constructors, methods, fields, properties, and events of a class, along with this the module and the assembly in which these information are present can be accessed and manipulated easily.

As mentioned earlier, we can use reflection to dynamically create an instance of any type, bind the type to an existing object, or get the type from an existing object. Once this is done appropriate method can be invoked, access the fields and properties. This can be done by specifying the Type of object or by specifying both assembly and Type of the object that needs to be created. By this the new object created acts like any other object and associated methods, fields and properties can be easily accessed. With reflection we can also find out about various methods associated with newly created object and how to use these object. To find out the attributes and methods associated with an object we can use the abstract class MemberInfo, this class is available under the namespace System.Reflection.

  Reflection can be used in following different ways to get different information about various Types.

All the below mentioned classes are available under the namespace System.Reflection.

 

  Assembly Class can be used to get the information and manipulate the assembly. This class allows us to define and load assemblies, load modules that are listed in the assembly manifest, and locate a type from this assembly and create an instance of it. Assembly.GetType or Assembly.GetTypes are the two methods that can be used to get the Type object from assemblies that have not been loaded. To these method name of the Type(s) is passed as the parameter. Type.GetType is used similarly as mentioned above only distinction is that here the assemblies are loaded.

 

Example: The following statement fetches mscorlib assembly information 

 

Assembly assemblyInformation = typeof(Object).Module.Assembly; 

 

// Loads an assembly using its file name 

Assembly assemblyInformation = Assembly.LoadFrom(“MyApplicationToRu n.exe”); 

 

// Fetch the types available in the assembly 

Type [] assemblyTypeInformation = assemblyInformation.GetTypes (); 

 

foreach (Type TypeInformation in assemblyTypeInformation) 

    Console.WriteLine (TypeInformation.FullName); 

}

As shown above once the Type is obtained, there are many ways you can fetch the information about the members of that type. For example, to find out about all the type’s members we can use the Type.GetMembers method, which obtains an array of MemberInfo objects describing each of the members of the current type.

Module Class is used for the reflection of the module. This class is used to get information about parent assembly, classes in the module, all the global methods available in the classes.

ConstructorInfo Class is used for the reflection of a constructor, and used to fetch the information about constructor also constructor can be invoked. Constructor information like name, parameters, access modifiers, and various implementation details (such as abstract or virtual) can be obtained. Class Objects are created when constructor of a ConstructorInfo is invoked this returns either the GetConstructors or GetConstructor method of a Type object.

Example: This program lists all the public constructors of the System.String class.

using System;
using System.Reflection;
class ReflectionConstructorInformation {
    public static void Main(String[] args)    {
        Type StringTypeObject= typeof(System.String);
        // Constructors.
        ConstructorInfo[] ConstructorInformation = StringTypeObject.GetConstructors(BindingFlags.Public | BindingFlags.Instance);

        foreach (MemberInfo memberInformationDetails in ConstructorInformation) 
        {
            Console.WriteLine (“{0}{1}”, ” “, memberInformationDetails);
        }
        Console.WriteLine();
    }
}
 

MethodInfo Class is used to obtain information such as the name, return type, parameters, access modifiers (such as public or private), and implementation details (such as ab,stract or virtual) of a any method inside the class, module, assembly. GetMethods or GetMethod method of a Type are used to on the to obtain the information.

FieldInfo Class, as the name suggest this class is used to get the information such as the name, access modifiers (such as public or private) and implementation details (such as static) of a field. Even to get or set field values of a class.

EventInfo Class is used to fetch the information about name, event-handler data type, custom attributes, declaring type, and reflected type of an event. This class is also used to add or remove event handlers.

PropertyInfo Class is used to fetch the information about the name, data type, declaring type, reflected type, and read-only or writable status of a property. Also we can get or set property values using this class.

ParameterInfo Class is used to fetch the information about parameter’s name, data type, whether a parameter is an input or output parameter, and the position of the parameter in a method signature. We can GetParameters method in this class that returns an array of ParameterInfo objects representing the parameters of a method, in order.

Another important namespace is System.Reflection.Emit Namespace. This name space can be used to create the type at run time and invoke as and when required. Basic usage of this namespace is to write the information to appropriate types. System.Reflection.Emit namespace contains classes that can be used by the compiler or tool to emit metadata and Microsoft intermediate language (MSIL). The compiler or script generators basically use this information.