Next step of programming

Just another WordPress.com weblog

Archive for September 17th, 2008

Listing Types and Methods of assembly, Reflection

with one comment

Some time there can be requirment in which we need to list the types and methods of assembly. For that purpose we have to use the reflection with help of that we can get all the details of the assembly even the IL code also. one samle to list the Types, associated methods and there properties is given below

//Get the assembly object                
Assembly assembly = Assembly.LoadFrom(openFileDlg.FileName);

//List them all                
foreach (Type type in assembly.GetTypes())
{
    //Create a node of types first                     
    TreeNodetreeNode = assemblyTreeView.Nodes.Add(type.Name);

    foreach (MethodInfo mthdInfo in type.GetMethods())
    {
        //Get the node as method name                        
        TreeNodemethodNode = treeNode.Nodes.Add(mthdInfo.Name);

        //List the details of the method as child node
        methodNode.Nodes.Add("Return Type : " +
            mthdInfo.ReturnType.ToString());
        methodNode.Nodes.Add("IsAbstract : " +
            mthdInfo.IsAbstract.ToString());
        methodNode.Nodes.Add("Access Modifier : " +
            (mthdInfo.IsPublic ? "Public" : "Private"));
        methodNode.Nodes.Add("IsStatic : " +
            mthdInfo.IsStatic.ToString());
    }
}

It is not limited to this much even you can create a type out of it and even can invoke methods of those type. This can be very useful when you want to create instance of class at runtime after locating in the various assemblies

Written by A.Sethi

September 17, 2008 at 10:27 am

Posted in C#, Reflection

Tagged with , , , ,