altandogan
altandogan

Reputation: 1285

Object change in C#

When I write this code I see an unexpected situation how can I solve this?

KurumReferans tempReferans = new KurumReferans();
tempReferans = kRef; 

if (kurumDetaylari.IsTakipMekanizmasiKullaniyor == true)
{
    KurumReferans kRefIstakip = new KurumReferans();
    kRefIstakip = kRef;
    kRefIstakip.Referans = "SORUMLU";
    kRefIstakip.Yontem = "SORUMLU:";
    kRefIstakip.Tipi = Tipi.Zorunlu;
    kRefIstakip.Parent = kurum;
    PostAddEdit(db.KurumReferans, kRefIstakip, cmd, "", "", "", "");
}

Firstly I assign,

tempReferans = kRef;

After when I assign kref to other object,

KurumReferans kRefIstakip = new KurumReferans();
kRefIstakip = kRef;
kRefIstakip.Referans = "SORUMLU";

tempReferans object's values change but I want to old values.

Upvotes: 0

Views: 108

Answers (2)

Shaharyar
Shaharyar

Reputation: 12459

In the line:

kRefIstakip = kRef;

the object kRef is also referenced by kRefIstakip. Because you are assigning kRef instance to kRefIstakip, not copying kRef to kRefIstakip.

In Reference Type objects, the code:

obj1 = obj2;

doesn't copy the values of obj2 to obj1, but it copies obj2 reference to obj1. And then both can access same memory location.

Upvotes: 0

Rajesh Subramanian
Rajesh Subramanian

Reputation: 6490

Your object is getting changed, because when you assign an object, it just assigns the address to it and both variable uses same memory space or object. To overcome this, you have to make a deep copy of the object and assign.

public static T DeepClone<T>(T obj)
{
 using (var ms = new MemoryStream())
 {
   var formatter = new BinaryFormatter();
   formatter.Serialize(ms, obj);
   ms.Position = 0;

   return (T) formatter.Deserialize(ms);
 }
}

EDIT: You have mark that class with attribute [Serializable]

Upvotes: 8

Related Questions