RE: how to get a copy of ref type object
From: Ansil MCAD (AnsilMCAD_at_discussions.microsoft.com)
Date: 12/02/04
- Next message: Chester Ragel: "WMI"
- Previous message: Shreeram Natarajan: "Error: Unable to load dll (coredll.dll) (.net cf)"
- In reply to: lion: "how to get a copy of ref type object"
- Next in thread: Sahil Malik: "Re: how to get a copy of ref type object"
- Reply: Sahil Malik: "Re: how to get a copy of ref type object"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 1 Dec 2004 21:13:06 -0800
hi
Take a look at
Object.MemberwiseClone Method
[MSDN]
This method cannot be overridden; a derived class should implement the
ICloneable interface if a shallow copy is not appropriate. MemberwiseClone is
protected and, therefore, is accessible only through this class or a derived
class.
A shallow copy creates a new instance of the same type as the original
object, and then copies the non-static fields of the original object. If the
field is a value type, a bit-by-bit copy of the field is performed. If the
field is a reference type, the reference is copied but the referred object is
not; therefore, the reference in the original object and the reference in the
clone point to the same object. In contrast, a deep copy of an object
duplicates everything directly or indirectly referenced by the fields in the
object.
For example, if X is an Object with references to the objects A and B, and
the object A also has a reference to an object M, a shallow copy of X is an
object Y, which also has references to objects A and B. In contrast, a deep
copy of X is an object Y with direct references to objects C and D, and an
indirect reference to object N, where C is a copy of A, D is a copy of B, and
N is a copy of M.
[/ MSDN]
this is the example in msdn
The following code example shows how to copy an instance of a class using
MemberwiseClone.
[C#]
using System;
class MyBaseClass {
public static string CompanyName = "My Company";
public int age;
public string name;
}
class MyDerivedClass: MyBaseClass {
static void Main() {
// Creates an instance of MyDerivedClass and assign values to its fields.
MyDerivedClass m1 = new MyDerivedClass();
m1.age = 42;
m1.name = "Sam";
// Performs a shallow copy of m1 and assign it to m2.
MyDerivedClass m2 = (MyDerivedClass) m1.MemberwiseClone();
}
}
regards
Ansil
"lion" wrote:
> in .net, if you set annstance-A of a class equal to another instance-B, a
> pointer will add to B, but if i want to create a copy of B instead of
> pointer, how to operate?
>
> Note:serialization isn't permitted
>
> 3x
- Next message: Chester Ragel: "WMI"
- Previous message: Shreeram Natarajan: "Error: Unable to load dll (coredll.dll) (.net cf)"
- In reply to: lion: "how to get a copy of ref type object"
- Next in thread: Sahil Malik: "Re: how to get a copy of ref type object"
- Reply: Sahil Malik: "Re: how to get a copy of ref type object"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|