DJ Burb
DJ Burb

Reputation: 2364

Object does not match target type when trying to use SetValue

public class ConflictSaver
{
    private readonly IEnumerable<CommonJobDataInfo> _conflictingJobData;
    private readonly DataAccessDataContext _dc;

    public ConflictSaver(IEnumerable<CommonJobDataInfo> conflictingJobData, DataAccessDataContext dc)
    {
        _conflictingJobData = conflictingJobData;
        _dc = dc;
    }

    public void Save()
    {
        foreach (var data in _conflictingJobData)
        {
            var type = data.ClientBaseObject.GetType();
            var formattedProperty = data.Property.Trim('.').ToUpper();
            foreach (var property in type.GetProperties())
            {
                var currentProperty = data.ClientBaseObject.GetType().GetProperties().First(t => t.Name.Trim() == property.Name.Trim());

                if(currentProperty.Name.ToUpper()== formattedProperty)
                {
                    if (data.UseServerValue)
                        currentProperty.SetValue(currentProperty, data.ServerValue, null);
                    else
                        currentProperty.SetValue(currentProperty, data.ClientValue, null);
                }
            }

        }
    }
}  

I get Object does not match target type in the Save() function when I try to call SetValue(). I stink at reflection.

Upvotes: 5

Views: 2684

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

It looks like you are using a wrong overload, and passing a wrong object:

if (data.UseServerValue)
    currentProperty.SetValue(data.ClientBaseObject, data.ServerValue);
else
    currentProperty.SetValue(data.ClientBaseObject, data.ClientValue);

The property belongs to data.ClientBaseObject, so it should be the invocation target. There is no idexer for that property, so if you are on .NET 4.5 or later, you can skip the third parameter altogether.

Upvotes: 3

Related Questions