Go to home page mail me! RSS Feed

Error - "Object does not match target type"

Wednesday, November 12, 2008 3:41 PM

Weird error that toke me a few autobot years to figure it out. Anyway, I got the following exception "System.Reflection.TargetException: Object does not match target type." when I tried to do some reflection, here is the code and off course as usual the error message wasn't descriptive enough.

foreach (object obj in this.InnerList)
{
    System.Reflection.PropertyInfo pi = obj.GetType().GetProperty(field);
    if (pi != null && pi.GetValue(obj,null).Equals(value))
        return obj;
}

 

The above code simply locates an object within a collection that has a property/field "field" that matches the specified value "value" - kind of a find/search function. Here is the fix.

foreach (object obj in this.InnerList)
{
    System.Reflection.PropertyInfo pi = obj.GetType().GetProperty(field);
    if (pi != null && pi.GetValue(Activator.CreateInstance(obj.GetType()), 
        null).Equals(value))
        return obj;
}
Can you spot the difference "Activator.CreateInstance", basically  the "GetValue()" method needs an instance of the object and not the object itself, and why in the world was that not stated in the error message.

Your Comments.

  • # re: Error - "Object does not match target type"

    Gravatartest

    Left by Rydal Williams at 11/16/2008 5:45 PM

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 2 and 5 and type the answer here:

Preview Your Comment.

 
Next entries »