ross dickinson: web and desktop software developer

Always Use Caution When Using MemberwiseClone

by Ross on December 8, 2010 at 1:04 PM under .NET

I guess it goes without saying, though some people may not realize just how careful they need to be if they're using the MemberwiseClone protected method on .Net objects.

Always remember that MemberwiseClone will copy *everything* from one object in to another. There's not much to worry about with value types, because those get copied into new values no matter what. Reference types, though, have their references copied. You might think, "Hey, great, I don't have to copy over my various reference type properties". What you always need to keep in mind, though, is this copies private fields and other references you may not have in your control.

This bit me when I was using MemberwiseClone on a very basic object I'd made that implemented INotifyPropertyChanged. No problem there right? Wrong! If I had any attached event listeners to the object's PropertyChanged event, those listeners got attached to the new copy as well. If I attempted to remove the handler from the original object, it would not be removed from the copy(and vice versa).

End point: You should probably avoid MemberwiseClone if at all possible and either manually set the properties that are needed, or come up with a better way to automate the cloning process.

Add comment

  • Comment
  • Preview

About the author

rossisdead is a 26 year old web and desktop software developer from New Jersey. He has two cats and likes long walks on the beach.

On Stackoverflow

On Stackoverflow Careers

On Codeplex

On Github