Please consider this code
some v1=new some();
v1.x=10;
some v2=v1;
v1.x=15;
Console.Write(v2.x);//Show 15
When I change x property on v1 why change value of x on v2?
Please consider this code
some v1=new some();
v1.x=10;
some v2=v1;
v1.x=15;
Console.Write(v2.x);//Show 15
When I change x property on v1 why change value of x on v2?
Because there is only one object instance.
The variables v1
and v2
are references to the same object. When you assign v1
to v2
you don't get a new instance of the object, you just copy the reference.
Because v1
is a reference to an object of type some
. When you state some v2 = v1;
you create a copy of this reference, not a copy of the actual object. To make a new object, you would need to instantiate the class again by running the constructor some v2 = new some();
.
because v2 is having referecne to v1 object that why
both v1 and v2 point same object i.e. same object reference.
some v2=v1;
its not copying its just copying reference
For creating copy of object refer this answer : Creating a copy of an object in C#
The exact behavior depends on the variable type, more precisely on whether the type is a value type or a reference type.
Here Point
is a struct
, i.e. a value type:
var p1 = new System.Drawing.Point(10, 20);
var p2 = p1; // This creates a copy of p1.
p1.X = 15;
Console.WriteLine(p1.X); // ==> 15
Console.WriteLine(p2.X); // ==> 10
This declaration, however, declares a reference type (classes are always reference types):
public class Vector
{
public Vector(double x, double y)
{
X = x;
Y = y;
}
public double X { get; set; }
public double Y { get; set; }
}
This will happen:
var v1 = new Vector(10.0, 20.0);
var v2 = v1; // Now the reference v2 points to the same object as v1.
v1.X = 15.0;
Console.WriteLine(v1.X); // ==> 15.0
Console.WriteLine(v2.X); // ==> 15.0
Variables of a reference type contain a reference to an object which is created dynamically by new
.
On the other hand the new
keyword only defines the values of a struct
, but do not create the struct
, as the variable contains the object itself.
It is a good idea to change the display color of value types in Visual Studio:
Menu: Tools > Options
You can change the display color of delegates, interfaces and enums as well. Like this you will immediately see that they are not (normal) classes in the editor of VS.