Cybercrux

Everything is achievable through technology

Reflection

Sample code

using System;
using System.Reflection;
namespace SampleConsole
{
class Program
{
static void Main(string[] args)
{
#region Practical implementation
//Use Dependency injection to create object
IMyClass myClassObj = new MyClass1();
//IMyClass myClassObj = new MyClass2();
// Get the Type information.
Type myTypeObj = myClassObj.GetType();
// Get Method Information.
MethodInfo myMethodInfo = myTypeObj.GetMethod("MyFunction");
object[] mParam = new object[] { 5, 10 };
// Get and display the Invoke method.
Console.Write(string.Format("\n Class Name:{0} \n\n Method Name:{1} \n\n Function Result: {2} \n\n"
, myTypeObj.Name, myMethodInfo.Name
, myMethodInfo.Invoke(myClassObj, mParam)));
#endregion
#region Extra Read
// Get Assembly info
System.Reflection.Assembly info = typeof(System.Int32).Assembly;
// Create Instence of Dynamic Type
Type typeobj = myClassObj.GetType();
object obj = Activator.CreateInstance(typeobj);
#endregion
Console.ReadLine();
}
}
public class MyClass1 : IMyClass
{
public int MyFunction(int numb1, int numb2)
{
return numb1 + numb2;
}
}
public class MyClass2 : IMyClass
{
public int MyFunction(int numb1, int numb2)
{
return numb1 * numb2;
}
}
interface IMyClass
{
int MyFunction(int numb1, int numb2);
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s