Hi all Im very new to .net. I have opted this site to learn. Now when Im going through the tutorials i made small code snippet for practice.
class myclass
{
int no;
string st;
}
main()
{
myclass temp = new myclass();
myclass ab = new myclass():
temp.no = 1;
temp = ab;
temp.no = 2;
ab.no =3;
After here no matter how changes i make to ab.. itz effecting temp also.. I understand it is taking as a reference. But please clarify me that if i want only contents to be copied what should I do.. Please dont mind I know Im asking very basic silly doubt.. Understand my prblem becoz I have come from C background.. Im getting hard to understand C#.
}
Loading
mahesh guptaPosted Mar 25, 2011, 3:11 PM
VulpesPosted Mar 25, 2011, 3:06 PM
using System;
class myclass
{
public int no;
public string st;
public myclass Clone()
{
return (myclass)this.MemberwiseClone();
}
}
class Program
{
static void Main()
{
myclass temp = new myclass();
temp.no = 1;
myclass ab = temp.Clone();
ab.no = 3;
Console.WriteLine(temp.no); // still 1
Console.ReadKey();
}
}
Incidentally, MemberwiseClone() creates a 'shallow' copy which is OK as long as your fields are all value types (int, double etc) or strings. You'd need to clone any reference type fields individually.
mahesh guptaPosted Mar 25, 2011, 3:05 PM
Guest UserPosted Mar 25, 2011, 3:03 PM
When these two lines execute:
myclass temp = new myclass();
myclass ab = new myclass():
You have two separate instances of myclass. But after this line:
temp = ab;
The variables temp and ab both point to the ab instance. The instance that was originally assigned to temp is no longer accessible and will be garbage-collected by .Net.
To copy one instance's properties to another, the quickest way would be to do something like this:
temp.no = ab.no; // copies the no value from ab to temp
temp.st = ab.st; // copies the st string reference from ab to temp