Showing posts with label Reflection. Show all posts
Showing posts with label Reflection. Show all posts

Friday, May 20, 2011

Reflection in C#

Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. In other words, reflection provides objects that encapsulate assemblies, modules and types.


namespace ReflectionLibrary
{
    public class MyClass
    {
        public virtual string AddNumb(int numb1, string numb2)
        {
            string result = numb1.ToString() + numb2;
            return result;
        }


    }
}


using System.Reflection;
using ReflectionLibrary;
namespace ConsoleApplication1
{
    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 = myClassObj.GetType().GetMethod("AddNumb");
            object[] mParam = new object[] { 5, "Vivek" };
            // Get and display the Invoke method.
            Console.WriteLine(myMethodInfo.Invoke(myClassObj, mParam));
            Console.ReadLine();
            return 0;
        }
    }
}