Reflection

Introduction

Reflection is used to get the information regarding assemblies,type of object,modules and classes at runtime. you can also create instances of type and assemblies at runtime,invoke methods of objects,get names of assemblies dynamically. it’s similar to Runtime type information in c++.

System.Reflection namespace used for reflection which contains all required classes and interfaces for related to reflection.

In the below sample program you can see by using typeof() method we are getting the type of class program and storing in Type1 variable and then creating instance for Type1. Then by using invoke member method we are invoking Add method and passing two parameters and finally storing the result in res variable.

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

namespace reflection
{
class Program
{
public int Add(int num1, int num2)
{
int result = num1 + num2;
return result;
}

static void Main(string[] args)
{
Type type1 = typeof(Program);
//Create an instance of the type
object obj = Activator.CreateInstance(type1);
object[] mParam = new object[] { 5, 10 };
//invoke AddMethod, passing in two parameters
int res = (int)type1.InvokeMember(“Add”, BindingFlags.InvokeMethod,
null, obj, mParam);
Console.Write(“Result: {0} \n”, res);
Console.ReadLine();
}
}
}

Thank you!

Advertisements

2 comments

  1. understood the prog, passing 2 para’s to the method and recieving the value from the method and stored into “res” para , but can u explain what is the reflection? i mean i want more description about this

    1. i suppose write the explaination for this but before that you post the comments. today i’ll do it.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: