Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the different between clone method and assign the instance to another directly

Tags:

c#

clone

I want to know, if I have a class named Test, what's the difference below

Test test = new Test();
Test newTest = test;
Test newTest2 = test.Clone();

What's the different between newTest and newTest2? Anyone can help? Thanks in advance!

like image 489
James Avatar asked Jan 25 '26 07:01

James


1 Answers

When you assign the instance, if Test is a class, you're actually copying the reference, but test and newTest will both point to the same instance in memory.

This means that both variables point to the same object:

Test test = new Test();
test.Foo = 24;
Test newTest = test;
newTest.Foo = 42;
Console.WriteLine(test.Foo); // Prints 42!

Clone(), on the other hand, typically is used to indicate a copy of the object itself, which means that test and newTest2 would point to different objects, so the above wouldn't happen.

Note that, if test is a struct (value type), then a direct assignment is effectively a full (shallow) copy of the object, by value.

like image 186
Reed Copsey Avatar answered Jan 27 '26 19:01

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!