Reflection with Property in C#

Reflection with Property in C#

We have already explained Extension Method in C#Reflection Introduction c#Insert data into Database table using SQLBulkCopy class in C#as keyword C#, Import/Upload Excel file in asp.net with C#The Microsoft Jet database engine cannot open the file. It is already opened exclusively by another user,   Call method after specific time interval C#Alert from code behind asp.net,required field validator in asp.net,Difference between RegisterClientScriptBlock and RegisterStartupScript asp.netDifference between ref and out parameters.

Today I am going to explain about how can we access public property information from any class using reflection. PropertyInfo object describes property of class and also acts as proxy when you want to either get or set property. Two methods use for getting any property information of class at runtime using reflection.

1) GetProperty() :-   GetProperty method used to get single property from class.

2) GetProperties() :-   GetProperties method used to get array of properties at runtime.

We can assign value to property by below method :

1) SetValue() :-  Set Value method used to set values to properties of that class.

Here I have created sample class which has three properties which includes nullable property type.

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

namespace ReflectionExample
{
    public class ClsPropertyDemo
    {
        public string strName { get; set; }
        public string strMarks { get; set; }
        public Int32 ? IntVariable { get; set;}

        public string GetPropertyMethod()
        {
            StringBuilder strfinal = new StringBuilder();

            if (!string.IsNullOrEmpty(strName))
                strfinal.Append("Name: "+strName + ", ");
            
            if (!string.IsNullOrEmpty(strMarks))
                  strfinal.Append("Marks: "+strMarks + ", ");

            if (!string.IsNullOrEmpty(Convert.ToString(IntVariable)))
                strfinal.Append("Age: "+IntVariable );

            return Convert.ToString(strfinal);
        }
    }
}

Below I have created one simple method named with “CallMethodWithProperty” in which we has assign property’s values and these properties value would be accessible by method name “GetPropertyMethod” :

private string CallMethodWithProperty()
{
    List<object> lstparams = new List<object>();

    // Here name of Assembly...
    string AssemblyName = "ReflectionExample";
    // Here classname with its NameSpace...
    string NamespaceName = "ReflectionExample.ClsPropertyDemo";  
    object objClassInstance = System.Activator.CreateInstance(AssemblyName, NamespaceName).Unwrap();
    object objMethodResult = new object();
    MethodInfo miMethod = null;
    Type tClsType = objClassInstance.GetType();
    MemberInfo[] mInfoMethods = tClsType.GetMember("GetPropertyMethod");
    if (mInfoMethods.Length == 1)
    {
        // Here we can get method from respective class...
        miMethod = tClsType.GetMethod(Convert.ToString("GetPropertyMethod"));  
    }
    else
    {
        // Here we can get method from respective class...
        List<Type> lstPrms = new List<Type>();
        miMethod = tClsType.GetMethod(Convert.ToString("GetPropertyMethod"), lstPrms.ToArray());        
    }
    PropertyInfo[] piInfo = tClsType.GetProperties();
    PropertyInfo piInfo1 = tClsType.GetProperty("strName");
    PropertyInfo piInfo2 = tClsType.GetProperty("IntVariable");
    PropertyInfo piInfo3 = tClsType.GetProperty("strMarks");

    object finalvalue = GetPropertyValue("Hello",piInfo1.PropertyType);
            piInfo1.SetValue(objClassInstance, finalvalue, null);
    finalvalue = GetPropertyValue(25,piInfo2.PropertyType);
            piInfo2.SetValue(objClassInstance, finalvalue, null);
    finalvalue = GetPropertyValue("Sohil", piInfo3.PropertyType);
            piInfo3.SetValue(objClassInstance, finalvalue, null);

    object strTempVar = miMethod.Invoke(objClassInstance,null);
    return (!string.IsNullOrEmpty(Convert.ToString(strTempVar))) ? Convert.ToString(strTempVar) : string.Empty;
}

OUTPUT: 

Reflection-with-Properties
Reflection-with-Properties

Folks you can contact me if you have any query regarding Reflection with Property in C#. You can also download working example of Reflection with Property in C#

Leave a Reply