How to Use Reflection in C#

How to Use Reflection in C#

Introduction:

Reflection is the process by which we get the reflection of our program. In simple words we get the meta data with the help of Reflection. Meta data contains the format of the data which is used in your program or the data types like int, float, double, string, class e.t.c.

Examples:

To explain this let us consider the following examples:

In order to use Reflection in your program you have to include the following library in your program:

 

//In the above mentioned line Type denotes the type of data which is used in your program. Now we have made the instance of Type as type.

 

 

In this line GetType() is a built in function which is included in the library

This function GetType() takes the format of the data types which are used in your program. i.GetType(); n shows that GetType() function will take the format of data related to i and store it in type which is the instance of Type.//

//This line will display the data type of i.

Output:

//The output is showing that the variable I has int type.//

Another Example:

 

 

//Now in this example Employee is the name of the class and employee is its instance. Now the line = new Employee(“john”, “3434-234344-3”, 20, 6);  shows that it will save the record new Employee(“john”, “3434-234344-3”, 20, 6); in the instance employee of  Employee class.//

//Now this line Typetype= employee.GetType(); will save the type of employee in type.//

//After the execution of this line the following result will be displayed:

Output:

//The above mentioned line is showing that employee has the data type of class known as Employee which is in class ClassActivities.

Another Example:

To demonstrate this further let us consider another example:

First make a class of Employee having the following code:

 

Now in the main we will do the following tasks:

 

Leave a Reply

Your email address will not be published. Required fields are marked *