First of all, I don't know if this is called "copying" an object, so the question title may be wrong. What I have is a custom class called File which has inside a bunch of lists (1000+ numbers in 5-6 lists) and some other properties. I have all my files in a List to be able to access them (LoadedFiles).
My question is: if I'm writing a method and I don't want to write:
DoSomeOperation(LoadedFiles[2]);
but instead:
File file2 = new File();
file2 = LoadedFiles[2];
DoSomeOperation(file2);
Is this a bad practice? Or the compiler is clever enough to know that it's the same object and access it directly from the original list (LoadedFiles).
Actually your class is a reference type which means that the line file2 = LoadedFiles[2] will only copy a reference pointer to the object that was created, you're not copying the contents of the object into a new object.
So as far as performance is concerned you a creating a new instance of a file:
File file2 = new File();
Then you're immediately switching the reference to a different object
file2 = LoadedFiles[2];
Thus releasing the reference to the object you had just created. This will cause needless garbage collection to occur. It's better to just do File file2 = LoadedFiles[2] if it makes a difference to you stylistically.
Best place to look into reference types vs value types is the C# Language specification http://www.microsoft.com/en-us/download/details.aspx?id=7029 on page 77.
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