blue 77
blue 77

Reputation: 37

value of that propertyObject does not match target type in c# (get property value with reflection)

I have a class that contain this property.

public List<string> Messages { get; set; }

I want to read value of that property with using reflection.

List<string> messages = new List<string>();
PropertyInfo prop = myType.GetProperty("Messages");
var message = prop.GetValue(messages);

but I get this error :

"Object does not match target type."

I used this line:

var message = prop.GetValue(messages,null);

instead of

var message = prop.GetValue(messages);

but still I get the same error.

Upvotes: 0

Views: 885

Answers (1)

Edin
Edin

Reputation: 1496

PropertyInfo contains the metadata about your Messages property. You can use that PropertyInfo to get or set the value of that property on some instance of that type. That means that you need to pass an instance of your type, from which you want to read the property Messages, into the GetValue call:

messages = (List<string>)prop.GetValue(instanceOfMyType);

Here is a working example of what you are trying to do:

class A
{
    public List<string> Messages { get; set; }

    public static void Test()
    {
        A obj = new A { Messages = new List<string> { "message1", "message2" } };
        PropertyInfo prop = typeof(A).GetProperty("Messages");
        List<string> messages = (List<string>)prop.GetValue(obj);
    }
}

Just for the record, this implementation makes no sense in real life, since you can get the value directly through obj.Messages

Upvotes: 2

Related Questions