how to use reflection to find the data type of a class property RRS feed

  • Question

  • I have a C# class called "equipment" with several defined properties with different data types; such as int, bool, string.  I use Reflection to with a variable name to find the property and set its value from a control's value, but before doing so, I would like to know the property's data type.  How can I do that?

    The following is an example of how I set the value:

    equipment equip = new equipment();
    PropertyInfo piInstance;

    for (int i = 0; i < pnlEquipmentDetails.Controls.Count; i++) { . . . TextBox tbm = (TextBox)pnlEquipmentDetails.Controls[i]; piInstance = typeof(equipment).GetProperty("equipmentName")); piInstance.SetValue(equip, tbm.Text, null); . . . }

    This works well if the type is string, but it the property is of type int, I need to parse tbm.Text.  How can I determine the property's type with Reflection?

    Rob E.

    • Edited by REvans611 Saturday, January 25, 2014 8:34 PM clarification
    Saturday, January 25, 2014 8:32 PM


  • You use the PropertyInfo.PropertyType property. For example:

    piInstance = typeof(equipment).GetProperty("equipmentName"));
    if (piInstance.PropertyType == typeof(string))
        piInstance.SetValue(equip, tbm.Text, null);
    else if (piInstance.PropertyType == typeof(int))
        piInstance.SetValue(equip, int.Parse(tbm.Text), null);

    Or more general:

    piInstance = typeof(equipment).GetProperty("equipmentName"));
    piInstance.SetValue(equip, Convert.ChangeType(tbm.Text, piInstance.PropertyType), null);

    Saturday, January 25, 2014 8:38 PM