Buildstarted
Buildstarted

Reputation: 26689

Transfering properties from one object to another with similar definition

There must be an easier way...

    void TransferFrom(object obj) {
        foreach(PropertyInfo prop in this.GetType().GetProperties()) {
            prop.SetValue(this, obj.GetType().GetProperty(prop.Name).GetValue(obj, null), null);
        }
    }

I have two separate libraries with the same object definition - all property names/types are the same. Is the above the only way to copy the values or is there another way? I'm unable to reference one of the dlls and the object to be copied is passed as an object rather than a distinct type.

Upvotes: 0

Views: 136

Answers (3)

STO
STO

Reputation: 10648

I'm not sure, but if classes in both assemblies have the same type name, you can try to use XmlSerializer by serializing instance of type from assemlby A then deserialize instance of type from assembly B from the same stream.

Upvotes: 0

Stephen Cleary
Stephen Cleary

Reputation: 456937

AutoMapper is flexible and powerful. I'm not sure if it'll work without referencing both types, but it's something to consider.

Upvotes: 1

Dan Bryant
Dan Bryant

Reputation: 27515

If you have control over both assemblies, take a look at Data Contracts, which were designed specifically to do what you're describing.

Upvotes: 1

Related Questions