Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Property by Name

Tags:

c#

reflection

I have a class with over 100 uniquely named properties and more than 20 child-classes, sometimes in lists. Below is a greatly simplified illustration of what I mean:

public class classA
    {
        public String PropertyA1 { get; set; }
        public int PropertyA2{get;set;}
        public List<classB> myList;
        public classC myClass { get; set; }

        public void SetProperty(String PropertyName)
        {
            // Match property name to property in this class or child class.
        }
    }

    class classB
    {
        public String PropertyB1 { get; set; }
        public bool PropertyB2 { get; set; }
    }

    class classC
    {
        public String PropertyC1 { get; set; }
    }

I would like to do two things that may or may not be possible. The first thing I need to do is iterate through every public property, including those of child classes and classes in a list, and translate the values. I know I can accomplish the parsing by serializing to xml and parsing through the results. I even have the code in place to convert to xml, as the function of the class is to build an xml object. However, I am worried that parsing through the xml might be much more expensive than accessing the properties through reflection. Can reflection be used in this manner, and would it be quicker than modifying the xml?

The other thing I would like to do is access any property passing the property name into a method. I realize I would need a separate method for accessing classes within lists, and may have to convert the list to a dictionary. The question is, would this be possible, and would the code only need to be in the parent class, or would each of the child classes need to repeat the code?

like image 780
Tim Avatar asked Jun 25 '13 19:06

Tim


1 Answers

Method that will set the property with the given name:

    public void SetProperty(String propertyName, object value)
    {
        this.GetType().GetProperty(propertyName).SetValue(this, value);
    }

A few things about the implementation:

  • The type used is the dynamic actual type of the object, that will find members that are in derived classes (as long as the object is of the derived type of course).
  • The property info has no idea of what object it came from, so this must be passed in again to the SetValue() call.

The second part of your question, to iterate through a list of properties, can be solved by using GetProperties() to get all the properties of the object, including inherited ones:

var properties = this.GetType().GetProperties();
like image 81
Anders Abel Avatar answered Nov 14 '22 20:11

Anders Abel