Send refrence types by value to a method

  • Thread starter Thread starter A.M
  • Start date Start date
A.M said:
Ho can I send a refrence type by value as a method parameter.

Well, the value of a reference type expression is a reference, and that
is passed by value by default.

You can't pass an actual *object* either by value or by reference.
 
Just by passing the reference type as parameter to a method without using
the ref or out keyword. You create a copy of the reference pointer on the
stack that points to the object on the heap..

Gabriel Lozano-Morán
Software Engineer
Sogeti
 
To add to Jon's and Gabriel's comments, if you want to pass a copy of
the object, it must be an object that implements ICloneable, and you
would clone it:

myObject.MyMethod(argumentObject.Clone());
 
Take in mind that this cloning is just a shallow copy

Gabriel Lozano-Morán
Software Engineer
Sogeti
 
Yes, usually. Of course, it depends upon how the class designer
implemented ICloneable, which never does specifically say whether a
clone should be a shallow copy or a deep copy.

Regardless, yes, a clone usually copies only the fields that are part
of the object being cloned, and does not copy objects to which the
cloned object holds references. So, in essence, by cloning you get:

1. A new object.
2. New copies of any value types (ints, doubles, DateTimes, structs)
that the object holds.
3. References to the same reference type objects to which the original
object held references.

Again, this depends upon how the class designer implemented ICloneable.

Of course, if the class doesn't implement ICloneable, then you can't
copy it using Clone(), and you only option is to create a new one using
"new" and whatever fields you can get at. Some classes (for example
System.Drawing.Font) work this way.
 
OK... so System.Drawing.Font implements ICloneable. D-Oh! Should have
checked first.

Anyway, there _are_ some classes that don't implement ICloneable, and
in those cases your only option is to use "new" and construct a new
object passing the properties of the object you want to copy.
 
Back
Top