Reputation: 14505
When I have this code:
class A
{
public int X = 0;
...
}
public void Function()
{
// here I create a new instance of class
A a = new A();
a.X = 10;
// here I create a pointer to null
A b = null;
// here I assign a to b
b = a;
b.X = 20;
}
did I pass the reference to instance of class A now? or I cloned the instance of A to new instance and created a reference to it in b?
is changing X in b also changing X in a? Why? If not, what is a proper way to create a copy of a and insert that to b?
Why the same with strings would always create a copy? Is equal operator overridden in strings?
string a = "hello";
string b = a;
b = "world";
// "hello world"
Console.WriteLine( a + " " + b );
Upvotes: 2
Views: 3827
Reputation: 98848
C# uses references not pointers. Classes are reference types
.
On your example, b
has the same reference with a
. They referencing the same location on memory.
changing X in b also changing X in a? Why?
Yes, because they reference to the same objects and changing one reference will affect the other one.
string a = "hello";
string b = a;
b = "world";
// "hello world"
Console.WriteLine( a + " " + b );
Strings are reference types also. But they are also immutable type
. Which means you can't change them. Even if you think you change them, you actually create new strings object.
"hello"
with a reference called a
.b
referencing to the same object. ("hello"
)b
reference new object called "world"
. Your b referance is not referencing "hello"
object anymore.Upvotes: 6
Reputation: 29233
When you assign, you pass a copy of the return value of the assigned expression.
Upvotes: 1
Reputation: 223392
did I pass the pointer to instance of class A now? or I cloned the instance of A to new instance and created a pointer to it in b?
b
is holding the same reference as a
, both of them pointing to the same location.
changing X in b also changing X in a? Why?
Because both of them are pointing to the same reference.
what is a proper way to create a copy of a and insert that to b?
Implement IClonable interface
Supports cloning, which creates a new instance of a class with the same value as an existing instance
EDIT
Since you edited the question with string, although strings are reference types but they are immutable as well
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.
Upvotes: 4
Reputation: 6490
Object b is pointing to the object a, you have to do the deep clone to make a copy using IClonable
Interface.
Upvotes: 1