Reflection

13:42




Create a new class library project and add 3 classes below:

public class ClassAge
    {
        public string getAge()
        {
            return "31";
        }
    }
class ClassName
    {
        public string getName()
        {
            return "Surajit";
        }
    }
class ClassAddress
    {
        public string getAddress()
        {
            return "Kolkata";
        }
    }

Add new console application below:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var myAssamble = Assembly.LoadFile(@"C:\Users\Surajit\Documents\Visual Studio 2015\Projects\ClassLibrary3\ReflectionClass\bin\Debug\ReflectionClass.dll");

            foreach (TypeInfo myType in myAssamble.GetTypes())
            {
                dynamic objMyClass = Activator.CreateInstance(myType);
                Type parameterType = objMyClass.GetType();
                
                foreach (MethodInfo methodInfo in parameterType.GetMethods())
                {
                    if (methodInfo.Name == "getAge" || methodInfo.Name == "getName" || methodInfo.Name == "getAddress")
                    {
                        Console.WriteLine("Class Name:" + parameterType.Name);

                        var valMethod = methodInfo.Name;
                        Console.WriteLine("Method Name:" + valMethod);

                        var valType = methodInfo.Name.GetType();
                        Console.WriteLine("Method Type:" + valType);

                        var valMethodReturn = methodInfo.Invoke(objMyClass, null);
                        Console.WriteLine("Method Return value:" + valMethodReturn);
                        Console.WriteLine("------");                        
                    }
                }
            }

            Console.ReadLine();
        }
    }
}

Output

Download

You can download application zip file here - 52 KB

You Might Also Like

0 comments