How To Invoke Method Using Reflection

May 02,2010 This Resource is About Reflection,In this Resource We have given a brief Explaination How To Invoke the Main Method of another Assembly .

Reflection: We can Get the Internal Details of Assembly Without having Access To Source Code.

First You Have To Import Reflection namespace in Your Application.

using System;
using System.Text;
using System.Reflection;

now Use Assembly class To Load the Target Assembly in Your Application.

Write this code in your Main method of the class.(wherever You want in a proper way but i am Write these Code in Main method)

Assembly assembly=Assembly.LoadFrom(string AssemblyPath);

now,second step is get the type information of the target Assembly

Type [] types=assembly.GetTypes();

Find out Type is Class Or Method

foreeach(Type t in types)
Console.WriteLine("Class Name Is: "+t.FullName);

MethodInfo [] methodname=t.GetMethods();

foreach(MethodInfo m in methodname)
Console.WriteLine("Method Name is :"+m.Name);
Console.WriteLine("Method Return Type: "+m.ReturnType);
object obj=Activator.CreateInstance(t) //1

string [] myarray={}; //2
m.Invoke(obj,myarray); //3

First Line:
In the Above Code I have Bold One Line it Will Create the Instance of the Class.

Second Line:
it Will Create a string Array without having any argument see ({ }).

Third line:
This is very important To Understand This Line Will Invoke the method.

m: Method Reference.
obj:class reference.
and last myarray reperesent that method does not have any argument..

if the Method have Argument Here You Have to Specified,i m not Covering this Tpic in This Article Just See My Another Article on Refelection

Hope this is Helpful for you Guys..


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: