Simon
Simon

Reputation: 6152

Why does Reflection's SetValue throw an exception?

I am trying to copy some property values from one object to another (both objects implement IVenue, but object b needs to have some values removed dynamically). Wanting to avoid a lot of code like:

a.Property1 = b.Property1;
a.Property2 = b.Property2;
etc

I am attempting to use Reflection to loop the properties and copy across:

public VenueContract(TVDData.Interfaces.IVenue v, List<TVDData.APIClientPermittedFields> permittedFields)
{
    PropertyInfo[] Properties = this.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo p in Properties)
    {
        PropertyInfo source = v.GetType().GetProperty(p.Name, BindingFlags.Public | BindingFlags.Instance);
        p.SetValue (p, source.GetValue(v,null),null);
    }
}

However I receive the error:

"Object does not match target type"

Both properties are type int, declared as:

public int ID { get; set; }

The problem appears to lie in p.SetValue as source.GetValue(v,null) returns the expected value.

Can anyone explain what I am doing wrong? Feel free to suggest a completely alternative approach if that would be a more appropriate solution.

Upvotes: 1

Views: 1568

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

Your first argument on SetValue is incorrect - it's try to set the property on the PropertyInfo.

You probably meant:

 p.SetValue(this, source.GetValue(v, null), null);

Upvotes: 4

Related Questions