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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With