Wednesday, July 02, 2008

Reflection-C#

This part is copied from Gopalan Suresh Raj's article for my reference purpose.

C# Reflection and Dynamic Method Invocation
Gopalan Suresh Raj

The Reflection API allows a C# program to inspect and manipulate itself. It can be used to effectively find all the types in an assembly and/or dynamically invoke methods in an assembly. It can at times even be used to emit Intermediate Language code on the fly so that the generated code can be executed directly.

Reflection is also used to obtain information about a class and its members. Reflection can be used to manipulate other objects on the .NET platform.

The Reflection API uses the System.Reflection namespace, with the Type class to identify the Type of the Class being reflected, and fields of a struct or enum represented by the FieldInfo class, Members of the reflected class represented by the MemberInfo class, Methods of a reflected class represented by the MethodInfo class, and parameters to Methods represented by the ParameterInfo class.

The Activator class's CreateInstance() method is used to dynamically invoke instances on the fly. Dynamic Invocation is very useful in providing a very late-binding architecture, where one component's runtime can be integrated with other component runtimes.

Obtaining All Classes and Their Type Information from an Assembly
using System;
using System.Reflection;

/**
* Develop a class that can Reflect all the Types available in an Assembly
*/
class ReflectTypes {

public static void Main (string[] args) {

// List all the types in the assembly that is passed in as a parameter
Assembly assembly = Assembly.LoadFrom (args[0]);

// Get all Types available in the assembly in an array
Type[] typeArray = assembly.GetTypes ();

Console.WriteLine ("The Different Types of Classes Available in {0} are:", args[0]);
Console.WriteLine ("_____");
// Walk through each Type and list their Information
foreach (Type type in typeArray) {
// Print the Class Name
Console.WriteLine ("Type Name : {0}", type.FullName);
// Print the name space
Console.WriteLine ("Type Namespace : {0}", type.Namespace);
// Print the Base Class Name
Console.WriteLine ("Type Base Class : {0}", (type.BaseType != null)?type.BaseType.FullName:"No Base Class Found...");
Console.WriteLine ("_____");
}
}
}