Wednesday, November 19, 2014

Reflection: Dynamically reading Object Properties and Calling Methods -- .NET


Introduction

In the .NET Framework, every program is compiled into an assembly containing metadata which has information of assembly behavior and structure. Reflection in .NET is used to observe and change the behavior of any object which means you can read read metadata of an object through reflection.

Current sample is going to describe following features of Reflection,
  1. Object properties and their datatypes.
  2. Call object methods dynamically. 
The first thing to use reflection in your project is, include the reflection namespace,

using System.Reflection;

Object properties and their datatypes

To read object Values from the object, we fist get the object type and call GetProperties method. 

Type myType = ObjectToProcess.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

In above code(first line), "ObjectToProcess" is class object which we need to process. The next thing is to loop through all the properties and get property name, datatype and value.

            foreach (PropertyInfo prop in props)
            {
                // getting property name
                string propertyName = prop.Name;
                //getting data type for property
                string propertyType = prop.PropertyType.Name;
                // getting property value
                object propertyValue = prop.GetValue(ObjectToProcess, null);

                
                Console.WriteLine(string.Format("Name: {0},  Value: {1},    Type: {2}", propertyName, propertyValue + "",propertyType));

            }

In the above code which getting the property value, the second parameter to GetValue function is used only for indexed properties. If you are using normal properties, you can use it null or can use the other override method which takes only one parameter which is object to be processed.

To set property value we can use following method,

prop.SetValue(ObjectToProcess, obj);

Calling object method dynamically

Followings are few lines that will call a subtract method with parameter from "objectToProcess" class object.

            Type myType = ObjectToProcess.GetType();
            MethodInfo myMethod = myType.GetMethod("Subtract"); 
            object[] myParam =new object[] {10, 5};
            myMethod.Invoke(ObjectToProcess, myParam);





No comments:

Post a Comment