<Blog:SatheeshBabu LiveAt="India"></Blog>    CodeDigest.com Latest 

Articles

         

Tuesday, November 08, 2005

Calling Function using Reflection

Reflection:

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.


Program:

using System;
using System.Reflection;

namespace ConsoleReflection
{
class Class1
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main(string[] args)
{
Assembly ass=Assembly.LoadFrom(@"C:\libraries.dll");
//Loading the dll
Type[] ty=ass.GetTypes();
//Gets all the types that is in the assembly libraries.dll
for(int j=0;j < ty.Length;j++)
{
if(ty[j].ToString()=="libraries.Class1")
{
object lib=ass.CreateInstance(ty[j].ToString());
//Creating instance for the type declared in the assembly
MethodInfo[] meth=ty[j].GetMethods();
//Getting alll the methods in the assembly
for(int i=0;i < meth.Length;i++)
{
if(meth[i].Name=="sum")
{
object[] param={1,2};
//Creating Parameter to invoke the function
object ans=meth[i].Invoke(lib,param);
//Invoking a method "sum" in the dll using Reflection int sum=int.Parse(ans.ToString()); Console.WriteLine("The output Calculated using Reflection is");
Console.Write(sum.ToString());
}
}
}
Console.Read();
}
}
}
}
OUTPUT:
The output Calculated using Reflection is
4
Libraries:
(A Class Library Project)
using System;
namespace libraries
{
public class Class1
{
public int sum(int a,int b)
{
return a+b;
}
}
}




Regards,
Satheesh

www.codedigest.com

0 Comments:

Post a Comment

<< Home