If I have a method like:
public SomeObject GetObject(int ID){
SomeObject obj1 = new SomeObject();
obj1.ID = ID;
return obj1;
}
Then if I used the method like this:
SomeObject obj2 = GetObject(4);
Will obj2 simply be a reference in memory to obj1, or will it be copied in memory and two complete objects exist?
And when would the GC remove obj1 from memory if the later is true?
It depends on the type. There are Value Types and Reference Types.
Value types store the value itself in memory and each time you pass it around you're just copying the value (thusly, value type) unless you use something like public void Test(ref int x). The fact that ref is there means to pass the integer, by reference.
When you have a variable of a reference type (object) you're basically just holding onto a pointer. So it would pass off the same reference of the object.
You can confirm this by extending your code to do something like this:
obj2.ID = 3;
Console.WriteLine(obj1.ID); // => 3
obj1 (or the object itself since obj1 is just a reference) will be GC'd when there are no longer any references to the object.
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