473,396 Members | 1,770 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,396 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 1332
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.