blog

Home / DeveloperSection / Blogs / Reflection in C#

Reflection in C#

priyanka kushwaha2586 27-Jan-2015

 In this blog, I’m explaining about Reflection in .Net

Reflection is the process by which program can read its own metadata. Reflection provides objects (typeof Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables to access them.

Example
namespace ReflectionProgram
{
 publicclassOperation
    {
    public  int add(int x, int y)
        {
            return (x + y);
        }
 
      public  int subtract(int x, int y)
        {
            return (x - y);
        }
      privatestring topic;
    }
 
 
   
  classProgram
    {
        staticvoid Main(string[] args)
        {
           Type  t  =typeof(Operation);
           MemberInfo[] mi = t.GetMethods();
            object[] parameters = newobject[2];
            parameters[0] = 32;
            parameters[1] = 12;
           object obj =Activator.CreateInstance(t);
              int res = (int)t.InvokeMember(mi[3].Name, BindingFlags.InvokeMethod,null, obj, parameters);
               Console.WriteLine(res);
           var info = typeof(System.Int32).Assembly;
           Console.WriteLine(info);
           Console.ReadKey();
        }
    }
}

Updated 27-Jan-2015

Leave Comment

Comments

Liked By