473,734 Members | 2,352 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

IClonable

If I want to implement an IClonable interface, how can I copy the events
from my source object to the target "cloned" object?
Nov 15 '05 #1
5 3661
If I want to implement an IClonable interface, how can I copy the events
from my source object to the target "cloned" object?

class CloneableWithEv ents : ICloneable
{
public event MyDelegate MyEvent;

public object Clone()
{
CloneableWithEv ents clone = new CloneableWithEv ents();
clone.MyEvent += MyEvent;
return clone;
}
}

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 15 '05 #2

"Mattias Sjogren" <ma************ ********@mvps.o rg> wrote in message
news:uZ******** ********@TK2MSF TNGP10.phx.gbl. ..
If I want to implement an IClonable interface, how can I copy the events
from my source object to the target "cloned" object?

class CloneableWithEv ents : ICloneable
{
public event MyDelegate MyEvent;

public object Clone()
{
CloneableWithEv ents clone = new CloneableWithEv ents();
clone.MyEvent += MyEvent;
return clone;
}
}


wouldn't

CloneableWithEv ents clone = (CloneableWithE vents)this.Memb erwiseClone();

be simpler? It catches private fields, including events(assuming they are
normal fields, not in a hash table or anything, and it will work when
overridden, the above method breaks when you inherit from it.

Mattias

--
Mattias Sjogren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

Nov 15 '05 #3
Daniel,
wouldn't

CloneableWithE vents clone = (CloneableWithE vents)this.Memb erwiseClone();

be simpler?
In this case, sure. But simpler isn't always better. :-) I didn't mean
to provide the definite way do handle this, just to show that it's
pretty straight forward and doesn't require any special magic.

It catches private fields, including events(assuming they are
normal fields, not in a hash table or anything, and it will work when
overridden,
MyEvent isn't virtual so you can't override it. ;-)

the above method breaks when you inherit from it.


If you expect your class to be inherited from (in code you don't
control) I would strongly suggest you avoid MemberwiseClone . You don't
know if the derived data can be safely be copied like that, or if it
for example references some unmanaged resource.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 15 '05 #4
thank's

"Mattias Sjögren" <ma************ ********@mvps.o rg> schrieb im Newsbeitrag
news:uZ******** ********@TK2MSF TNGP10.phx.gbl. ..
If I want to implement an IClonable interface, how can I copy the events
from my source object to the target "cloned" object?

class CloneableWithEv ents : ICloneable
{
public event MyDelegate MyEvent;

public object Clone()
{
CloneableWithEv ents clone = new CloneableWithEv ents();
clone.MyEvent += MyEvent;
return clone;
}
}

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

Nov 15 '05 #5
> If you expect your class to be inherited from (in code you don't
control) I would strongly suggest you avoid MemberwiseClone . You don't
know if the derived data can be safely be copied like that, or if it
for example references some unmanaged resource.


You're missing the point of MemberwiseClone then.

The correct way to clone a base-class object is as follows:

public virtual object Clone()
{
//perform shallow copies of all members, even derived ones
MyClass clone = (MyClass)Member wiseClone();

//perform deep copies where required
clone.deepCopyV alue = (ContainedClass )deepCopyValue. Clone();

//I usually disconnect any events here, actually
//since I don't usually want event handlers cloned

//finally
return clone;
}
This way any sub-classes of MyClass will automatically get a correct clone
of the base class. If the derived classes need a deep copy of anything
else, they can override Clone as follows:

public override object Clone() {
//allow base class to do its work, and deep copy anything it needs to
MySubClass clone = (MySubClass)bas e.Clone();

//if any of the derived members need to be deep-copied, do that here:
clone.collectio n = new MyCollection(co llection);

return clone;
}

It's up to each class to deep-copy any members that it needs. If the
sub-class fails to do so, it's the fault of the sub-class. At least with
the base-class using MemberwiseClone , sub-classes don't need to override
Clone unless they need to provide further deep-copying. Many times,
shallow-copies are perfectly acceptable.

If you don't use this method, you either need to provide a means for
sub-classes to safely clone all of the members of the base class (by making
them protected, perhaps), or through the use of
copy-constructor-like-semmantics (which then require all sub-classes to
follow a pattern which isn't very intuative to most C# programmers).

Using any other method (especially methods where Clone isn't marked virtual)
makes it the job of every derived class to ensure that the base class is
cloned properly.

Using the method I've described makes it the job of each class to deep-copy
only the members that it needs to. Sub-classes need not worry about how to
clone the parent class. This helps versioning as well---in case the parent
class introduces new members that require deep copies that the child class
is not aware of.

It seems to me that NOT using MemberwiseClone is more fragile than using it.
Or am I missing some obvious better way to implement cloning? I know
copy-constructors can work, but it's not nearly as elegant as a virtual
Clone implemented with MemberwiseClone and further deep copying.

--Matthew W. Jackson
Nov 15 '05 #6

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

Similar topics

3
2101
by: AMerrell | last post by:
Hello, There is a C# funciton I'm trying to translate that clones some event handlers. public virtual object Clone() { ...... Instance of a Custom Collection ....... myCol.ItemAdded = this.ItemAdded; myCol.ItemRemoved = this.ItemRemoved; return myCol;
2
3265
by: Dan | last post by:
I have an object that I want to add to an ArrayList. However, I don't know ahead of time how many objects I will need to add to the list. Therefore, I had built a function that created an instace of the object, set its properties, and then added it to the ArrayList. The function would then adjust the properties of the object and again add that object to the ArrayList. The problem I am having is that the changes I make to, what I thought...
7
3752
by: Tiësto | last post by:
Hi everybody. I know everyone has said to me that this doesn't exist but I'm going to try anyway. I have an instance of ClassA and I want to duplicate that instance, creating another one that is independient of the first one. Isn't there any automatic way to do this? Do I have to write IClonable implementation for each and every class? Best Regards
1
2338
by: oDDskOOL | last post by:
I realized today that the Hashtable.Clone only produces a shallow copy... that makes me go mad that M$ doesn't even provide a deep copy ctor for the Hashtable class ! mighty tech ducks might reply "oh but what if the types in hastable don't have copy ctors defined? that could lead to dangerous situations". well, but was it a significant effort to provide a copy ctor / deep clone method to this class for objects that provide the...
14
2719
by: Arne | last post by:
In C++ we have a copy constructor. What is the equivalent in .Net? Would that be a clone method?
2
19469
by: Nathan | last post by:
I'm working with Clone() for the first time, and noticed that you have to unbox the Clone of an object that implements ICloneable: MyObject var1 = new MyObject(); // Where MyObject implements ICloneable MyObject va3 = (MyObject)var1.Clone(); Does anyone know why the 2.0 framework doesn't include a Generic implementation of the ICloneable interface?
6
1832
by: Larry Minton | last post by:
Is there a C++ method comparable to the vb.net TryCast function? I had hopes for Convert::ChangeType, but that didn't work. For a scripting engine, the user is specifying to retrieve an interface on an object by name. Code is roughly: array<Type^> ^l_pInterfaces = l_pType->GetInterfaces(); for(int m=0; m < l_pInterfaces->Length; m++) { Type^ l_pInterface = l_pInterfaces;
2
10116
by: bonk | last post by:
I have come across the need to distinguish between the creation of a deep and a shallow copy and with great interest I have read this article: http://blogs.msdn.com/brada/archive/2004/05/03/125427.aspx This artivle seems to hint that I should not use System.IClonable but instead define my own interface(s) for cloning. Now since this article is rather old and since they did not obsolete IClonable there might be a new "best practise".
15
2733
by: Gustaf | last post by:
Using VS 2005. I got an 'IpForm' class and an 'IpFormCollection' class, containing IpForm objects. To iterate through IpFrom objects with foreach, the class is implemented as such: public class IpFormCollection : IEnumerable<IpForm> { ArrayList forms = new ArrayList(); public IEnumerator<IpFormGetEnumerator() {
0
8951
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8783
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9248
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9187
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6743
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6040
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4555
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4818
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2184
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.