none
Strange behavior using reflection RRS feed

  • Question

  • Hi!!

    I'm having some strange behavior using reflected types. I have my custom class and there is a custom property inside that class. Using reflection I need to create an instance of the type used by the property wich is also a custom class, so:

    PropertyInfo[] properties = myClass.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
               propertyClass pc = Activator.CreateInstance(property.PropertyType);
               ((propertyClass)pc).Value = "test value";
               property.SetValue(this, pc, null);
            }
    

    Assuming that Activator class should create an instance of the property type, that code should work, but It throws an exception when I try setting the property value through reflection:

    Object does not match target type.

    Any advice?

    Thanks!!

    Wednesday, October 31, 2012 5:28 PM

Answers

  • Ha! I found the solution. Obviously I was doing something wrong. In line 6, on SetValue method, the first parameter should be changed for the object that holds the reflected property. Of course, that object was myClass, no this.

    Thanks everyone!!
    • Edited by lemeridas Friday, November 2, 2012 1:17 PM
    • Marked as answer by lemeridas Monday, November 5, 2012 10:25 AM
    Friday, November 2, 2012 1:16 PM

All replies

  • Can you show your actual code?  The above won't compile, so it's obviously not the same (exactly) as what you're doing...


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Wednesday, October 31, 2012 5:33 PM
    Moderator
  • The code shown only makes sense if propertyClass has a Value property and a SetValue method. Is propertyClass the type name of the type of the property?

    Wednesday, October 31, 2012 10:41 PM
  • Reed is right, however, as a rule you should at least have something like

    if (property.ProteryType is propertyClass)
    {
    
    }

    You should get the property to make sure that it's of the type you're expecting. IF that's property type is a string it'll fail. Or use object pc instead of propertyClass pc.

    • Proposed as answer by Mike FengModerator Thursday, November 1, 2012 11:24 AM
    • Unproposed as answer by lemeridas Monday, November 5, 2012 10:25 AM
    Thursday, November 1, 2012 3:54 AM
  • Ha! I found the solution. Obviously I was doing something wrong. In line 6, on SetValue method, the first parameter should be changed for the object that holds the reflected property. Of course, that object was myClass, no this.

    Thanks everyone!!
    • Edited by lemeridas Friday, November 2, 2012 1:17 PM
    • Marked as answer by lemeridas Monday, November 5, 2012 10:25 AM
    Friday, November 2, 2012 1:16 PM