Reputation: 4371
I've been told that when you pass an Object to a method, it's passed "by value". I made a little test to examine it:
Point p = new Point(1, 1);
Circle c = new Circle(p);
p.x = 999;
Console.WriteLine(c.p.x);
the code above prints "999", but I thought the object is copied to the method
I've been told that if you're not using "ref" (or "out") the method get the value
of the object.
can someone make it clear to me?
thanks,
socksocket
Upvotes: 1
Views: 2111
Reputation: 7067
In .NET, there are two categories of types, reference types and value types.
Structs are value types and classes are reference types.
The general different is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.
A variable containing a value type contains the entire value type value. For a struct, that means that the variable contains the entire struct, with all its fields.
A variable containing a reference type contains a pointer, or a reference to somewhere else in memory where the actual value resides.
This has one benefit, to begin with:
Internally, reference types are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:
When you declare variables or fields, here's how the two types differ:
See MSDN and this tutorial is similar to your Circle / Point / Axises Example.
Upvotes: 1
Reputation: 39670
Assuming Point
is declared as class, not p
itself is copied, the reference to p
is copied. So it's still pass by value. You pass the value of a reference.
When saying Point p = new Point(1, 1);
(and if point is a reference type), one might think it is a variable containing a Point
, but in fact it is a variable containing a reference to a Point
that is stored somewhere else.
Upvotes: 3
Reputation: 301637
C# is pass-by-value - the reference value is passed in the normal case, that is. ( which means that it is a new reference to the same object)
Upvotes: 1