Reaperino
Reaperino

Reputation: 145

Copy every field of a class instance to another class instance to keep the data binding

I have a class instance of my class Poste (let's call it A) that has a DataBinding with my interface.

What I want to do is to copy every single property of another Poste class instance (I'll call it B) without losing the data binding of A with my interface.

What I naively first did :

//A already created
Poste B = new Poste();
A = B;

Of course it didn't worked because it passed the references.

After that I heard about shallow copy and deep copy so I tried to do a deep copy of my B class instance to A. (used deep copy class on internet, it's working)

A = ObjectExtensions.Copy(B); //making a deep copy of B into A

I thought it would copy B on the same A instance but still the data binding was not working anymore because INotifyPropertyChanged was not triggered.

So is there any simple way to copy every single field and property of a class without changing the current instance and losing the data binding ?

Upvotes: 0

Views: 382

Answers (1)

mm8
mm8

Reputation: 169150

What I want to do is to copy every single property of another Poste class instance (I'll call it B) without losing the data binding of A with my interface.

Then you should set every property of the existing instance of A. You may do this using reflection:

PropertyInfo[] properties = A.GetType().GetProperties();
foreach (var property in properties)
{
    if (property.CanWrite)
        property.SetValue(A, property.GetValue(B));
}

Upvotes: 1

Related Questions