I have a general question about a deep and shallow copy in the context of the pass-through concept and the pass-by-value concept of C #:
In C #, you need to explicitly create methods that accept pointers / references in order to be able to pass them to a method. However, at least the objects passed as parameters to the methods / constructors behave differently than the others. They seem to always be passed by reference unless additional cloning is performed, as described here: http://zetcode.com/lang/csharp/oopii/ .
Why are objects automatically passed by reference? Is there any particular benefit of forcing the cloning process for them instead of considering objects like int, double, boolean, etc. In these cases?
Here is a sample code that illustrates what I mean:
using System; public class Entry { public class MyColor { public int r = 0; public int g = 0; public int b = 0; public double a = 1; public MyColor (int r, int g, int b, double a) { this.r = r; this.g = g; this.b = b; this.a = a; } } public class A { public int id; public MyColor color; public MyColor hiddenColor; public A (int id, MyColor color) { this.id = id; this.color = color; } } static void Main(string[] args) { int id = 0; MyColor col = new MyColor(1, 2, 3, 1.0); A a1 = new A(id, col); A a2 = new A(id, col); a1.hiddenColor = col; a2.hiddenColor = col; a1.id = -999; id = 1; col.a = 0; Console.WriteLine(a1.id); Console.WriteLine(a2.id); Console.WriteLine(a1.color.a); Console.WriteLine(a2.color.a); Console.WriteLine(a1.hiddenColor.a); Console.WriteLine(a2.hiddenColor.a); } }
This leads to:
-999 0 0 0 0
MyCol instances MyCol always passed by reference, and the rest of the arguments are passed by value. I would have to implement ICloneable in the MyColor and A classes. On the other hand, the isf'-operator is present in C #, which should be used to explicitly enable and execute pass-by-reference.
Suggestions are welcome!
pass-by-reference pass-by-value c # clone shallow-copy
Florian R. Klein
source share