Many .Net interview question lists (including the good ones) contain the question: \"What is Reflection?\". I was recently asked to answer this in the context of a 5 questio
By using Reflection in C#, one is able to find out details of an object, method, and create objects and invoke methods at runtime.
using System;
using System.Reflection;
public class MyClass
{
public virtual int AddNumb(int numb1,int numb2)
{
int result = numb1 + numb2;
return result;
}
}
class MyMainClass
{
public static int Main()
{
// Create MyClass object
MyClass myClassObj = new MyClass();
// Get the Type information.
Type myTypeObj = myClassObj.GetType();
// Get Method Information.
MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
object[] mParam = new object[] {5, 10};
// Get and display the Invoke method.
Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " +
myMethodInfo.Invoke(myClassObj, mParam) + "\n");
return 0;
}
}
below code will get the type information:
Type myTypeObj = Type.GetType("MyClass");
The code snippet below will get the method's information
Methodinfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
The following code snippet will invoke the AddNumb method:
myMethodInfo.Invoke(myClassObj, mParam);