473,320 Members | 1,848 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Making a cloned or copied object...

I have a custom class that basically consists of two elements, a name
(String) and value (object). I am a bit confused on how to clone or
make a copy of an instance of my object. If I have:

public class MyItem {
private string name;
private object value;

public MyItem() {
}

public string Name { get{...} set{...} }
public object Value { get{...} set{...} }
}

how do I make sure that it is a true copy, with no cross references?
If I added a Clone method something like this:

public MyItem Clone() {
MyItem temp = new MyItem();
temp.Name = this.name;
temp.Value = this.value;
}

wouldn't the name and value refer to the original instances of name and
value? How would I truly copy objects?

Jul 21 '05 #1
7 1327
You can use binary serialization to create a clone or your object that is
truly separate from your original object. You'll need to add the
[Serializable] attribute to your class but it's pretty simple code to
implement.

[Serializable]
public class MyItem : ICloneable
{
private string _name;
private object _value;

public MyItem()
{
}

public string Name { get{ return _name; } set{ _name = value;} }
public object Value { get{ return _value; } set{ _value = value;} }

public object Clone()
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, this);
ms.Position = 0;
return formatter.Deserialize(ms);
}
}

HTH,
Jorge

"cmelnick" wrote:
I have a custom class that basically consists of two elements, a name
(String) and value (object). I am a bit confused on how to clone or
make a copy of an instance of my object. If I have:

public class MyItem {
private string name;
private object value;

public MyItem() {
}

public string Name { get{...} set{...} }
public object Value { get{...} set{...} }
}

how do I make sure that it is a true copy, with no cross references?
If I added a Clone method something like this:

public MyItem Clone() {
MyItem temp = new MyItem();
temp.Name = this.name;
temp.Value = this.value;
}

wouldn't the name and value refer to the original instances of name and
value? How would I truly copy objects?

Jul 21 '05 #2
I forgot to mention that I threw in the IClonable interface since the class
has a "Clone" method anyway.

"Jorge L Matos" wrote:
You can use binary serialization to create a clone or your object that is
truly separate from your original object. You'll need to add the
[Serializable] attribute to your class but it's pretty simple code to
implement.

[Serializable]
public class MyItem : ICloneable
{
private string _name;
private object _value;

public MyItem()
{
}

public string Name { get{ return _name; } set{ _name = value;} }
public object Value { get{ return _value; } set{ _value = value;} }

public object Clone()
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, this);
ms.Position = 0;
return formatter.Deserialize(ms);
}
}

HTH,
Jorge

"cmelnick" wrote:
I have a custom class that basically consists of two elements, a name
(String) and value (object). I am a bit confused on how to clone or
make a copy of an instance of my object. If I have:

public class MyItem {
private string name;
private object value;

public MyItem() {
}

public string Name { get{...} set{...} }
public object Value { get{...} set{...} }
}

how do I make sure that it is a true copy, with no cross references?
If I added a Clone method something like this:

public MyItem Clone() {
MyItem temp = new MyItem();
temp.Name = this.name;
temp.Value = this.value;
}

wouldn't the name and value refer to the original instances of name and
value? How would I truly copy objects?

Jul 21 '05 #3
Jorge L Matos wrote:
You can use binary serialization to create a clone or your object that is
truly separate from your original object. You'll need to add the
[Serializable] attribute to your class but it's pretty simple code to
implement.

[Serializable]
public class MyItem : ICloneable
{
private string _name;
private object _value;

public MyItem()
{
}

public string Name { get{ return _name; } set{ _name = value;} }
public object Value { get{ return _value; } set{ _value = value;} }

public object Clone()
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, this);
ms.Position = 0;
return formatter.Deserialize(ms);
}
}

HTH,
Jorge


Sorry to jump in here, but I wanted to ask... Is this the same as:

<Serializable()> _
Public Class clsCard

in VBNet2003?

I couldn't figure out the ICloneable item, it seemed to cause an error
in VBN2003.

Also having Option Strict turned on caused an error with the line
"return formatter.Deserialize(ms);" I think I took care of that, though.
Jul 21 '05 #4
Jorge L Matos wrote:
[Serializable]
public class MyItem : ICloneable
{ [...] public object Clone()
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, this);
ms.Position = 0;
return formatter.Deserialize(ms);
}
}


Is it impossible to close an object with Option Strict On?

I use the above serialization technique and get an error on the return
line. The error is:

Object Strict On disallows implicit conversions from 'System.Object' to
MyApp.MyClass

How can I avoid this build error? Thanks for any help!
Jul 21 '05 #5
Erin Anderson <er******@indy.net> wrote:
Is it impossible to close an object with Option Strict On?

I use the above serialization technique and get an error on the return
line. The error is:

Object Strict On disallows implicit conversions from 'System.Object' to
MyApp.MyClass

How can I avoid this build error? Thanks for any help!


Cast the result of the clone to the appropriate type. It's only
*implicit* conversions which are disallowed.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #6
Jon Skeet [C# MVP] wrote:
Erin Anderson <er******@indy.net> wrote:
Is it impossible to close an object with Option Strict On?

I use the above serialization technique and get an error on the return
line. The error is:

Object Strict On disallows implicit conversions from 'System.Object' to
MyApp.MyClass

How can I avoid this build error? Thanks for any help!

Cast the result of the clone to the appropriate type. It's only
*implicit* conversions which are disallowed.


I did a DirectCast, which seems to have helped. Thank you for the pointer!
Jul 21 '05 #7
Erin,

Try using DirectCast():

Dim myobj as MyApp.MyClass = DirectCast(myobj.Clone(), MyApp.MyClass)

Option Strict On - means that VB will force you to cast the return value
from the Clone() method from "Object" to the type you realy want.

--
Jorge L. Matos

"Erin Anderson" wrote:
Jorge L Matos wrote:
[Serializable]
public class MyItem : ICloneable
{

[...]
public object Clone()
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, this);
ms.Position = 0;
return formatter.Deserialize(ms);
}
}


Is it impossible to close an object with Option Strict On?

I use the above serialization technique and get an error on the return
line. The error is:

Object Strict On disallows implicit conversions from 'System.Object' to
MyApp.MyClass

How can I avoid this build error? Thanks for any help!

Jul 21 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: sonic | last post by:
Hello, I am cloning a table row which contains images that have behaviors attached to them as well as onclick events. The problem is that the cloned row seems to be executing the...
0
by: deko | last post by:
For some reason this is eluding me... I have a subform datasheet that contains appointments imported form Outlook. If the appointment is associated with an Entity in the database, it will have a...
9
by: cmelnick | last post by:
I have a custom class that basically consists of two elements, a name (String) and value (object). I am a bit confused on how to clone or make a copy of an instance of my object. If I have: ...
15
by: Sam Kong | last post by:
Hello! I got recently intrigued with JavaScript's prototype-based object-orientation. However, I still don't understand the mechanism clearly. What's the difference between the following...
3
by: markww | last post by:
Hi, I have a wrapper around some 3rd party database library function. The pseudo code looks like the following - it is meant to open a table in a database, extract values from a table, then copy...
7
by: rossum | last post by:
Is there any way of creating a read only reference to an array? My class includes a private array of bytes with a Property to access it. However, I do not want users to use the returned reference...
11
by: priyapratheep | last post by:
Hi friends, I am strugging with this problem.I don't know much javascript. Please you gurus can help me. My problem is I cloned the frist row in a table.after cloning i want to change the names...
4
by: silverleaf | last post by:
I'm starting to learn how to use the Allegro library with C++ on my own. My compiler is MSVisual C++ 6.0. The book I am learning out of is "Game Programming All In One, Third Edition" by Jonathan...
50
by: Juha Nieminen | last post by:
I asked a long time ago in this group how to make a smart pointer which works with incomplete types. I got this answer (only relevant parts included): ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.