I have a general question about deep- and shallow-copy in the context of the pass-by-reference- and pass-by-value-concept of C#:
In C# it is a requirement to explicitly create methods that accept pointers/references to be able to pass such to the method. However, at least objects passed as parameters to methods/constructors are behaving differently from the rest. It seems they are always passed by reference if no extra cloning is done as described here: http://zetcode.com/lang/csharp/oopii/.
Why are objects automatically passed by reference? Is there any particular benefit from forcing the cloning process for them instead of treating objects more like int, double, boolean, etc. in these cases?
Here is code example 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 results in:
-999
0
0
0
0
Instances of MyCol
are always passed by reference while the other arguments are passed by value. I would have to implement ICloneable in classes MyColor
and A
. On the other hand, the ´ref´-statement is present in C# which should be used to explicitly allow and do pass-by-reference.
Suggestions al welcomed!
double*
andTimeSpan*
are types of pointers. Those pointers can actually be incremented, or an integer can be added to them, and similar "arithmetic". The references related toclass
types don't have that. They are just "arrows" with no "addresses" (in C#, actual implementation might use addresses, of course, but that is invisible to the user). – Selfexistent