Passing objects by value

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Heres a dumb one. I know you can't actually pass reference types by value in
C#, but I want to pass an object into a method and allow that method to
manipulate a copy of that object, such that the original object is unchanged.
There's got to be an easy way to do this. Anyone have a suggestion?
 
Implement the IClonable interface in order to clone the object. When you
pass in your object, call the Clone() method.

Chris
 
Hi Arghnork,

Before you pass the object, make a copy of it and pass the copy. The
implementation depends on the object you are passing. If all of the members
are primitive types, you can take advantage of the Object class's
MemberwiseClone. However, since the MemberwiseClone method only creates a
shallow copy, it may not meet your needs if your object has an object graph
with references to other objects. The MemberwiseClone will copy references,
but will not follow the graph, which means that the copy and the original
will reference the same object.

If you need a deep copy, there is some debate as to whether you should
implement IClonable or your own mechanism. Here's a discussion on the
subject and, as you will see, there are many opinions:

http://tinyurl.com/5jpxr

Joe
 
Others have mentioned cloning, which is fine if you are in control of the object or it supports cloning. Howerver, if neither of these are true but the object is serializable, you can serialize it into a memory stream and deserialize a new instance, the passing that into the method.

If you have none of thse situations then what you want isn't possible AFAIK

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<[email protected]>

Heres a dumb one. I know you can't actually pass reference types by value in
C#, but I want to pass an object into a method and allow that method to
manipulate a copy of that object, such that the original object is unchanged.
There's got to be an easy way to do this. Anyone have a suggestion?

---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.768 / Virus Database: 515 - Release Date: 22/09/2004



[microsoft.public.dotnet.languages.csharp]
 
Yeah, that's actually my problem. My object is complex with a lot of
additional object references, so I was hoping someone had a "cleaner" way
than implementing the IClonable interface. I was trying to avoid entending
the object and adding my own Clone method. I guess I'm just being lazy.
..Net will do that to you. ;-)
 
Good suggestion. I had thought of serializing it, but was thinking file and
overlooking a memory stream. That might be a little slow, but speed isn't
really a serious concern.
 
Back
Top