Malcolm
Malcolm

Reputation: 12864

Using reflection copy object properties to another object

HI,

I have code below but getting error "object does not match target type" on the prop.SetValue statement. But the types are both Int32.

    private UniqueProjectType CreateUniqueProjectType(TBR.Domain.Project project)
    {
        UniqueProjectType type = new UniqueProjectType();

        foreach (PropertyInfo prop in type.GetType().GetProperties())
        {
            if (prop.Name == "ID")
            {}
            else if (prop.Name == "PayFrequency")
                type.PayFrequency = _tbrService.GetEmployee((int)project.EmployeeID).PayFrequency;
            else
                prop.SetValue(type, prop.GetValue(project, null), null);

        }

        return type;
    }

Upvotes: 1

Views: 4183

Answers (2)

Johann Blais
Johann Blais

Reputation: 9469

I think you should call GetValue on the PropertyInfo corresponding to the Project type. PropertyInfo instances are tied to a specific type.

Basically, for each property info of the UniqueProjectType type, you have to look for a PropertyInfo on the Project type with the same name. Then you call GetValue and SetValue for the two objects using their corresponding PropertyInfo.

Upvotes: 2

Migol
Migol

Reputation: 8448

I think here's the catch:

prop.GetValue(project, null);

prop is specific to UniqueProjectType while project is TBR.Domain.Project type. I think you should get all properties of TBR.Domain.Project and find one that has corresponding name.

Upvotes: 2

Related Questions