Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating object without reference

Tags:

c#

.net

Just have a few questions in my mind...

  1. Is it a good practice to create an object without reference like the one below. If so, why?

    LoadIt(new myClass()); where LoadIt is some method

  2. What happens to the object created above. Will that be garbage collected. If so when? ie, is its scope same as other objects

  3. Is there any chance of referring the same object again?

like image 592
Amsakanna Avatar asked Dec 02 '25 01:12

Amsakanna


1 Answers

The scope is decided by the Method (here LoadIt)...

If the Load it methods stores its myClass parameter in a global variable, then until the global variable goes out of scope, the Object will stay in the memory... ie. It will not be garbage collected as the global variable is still referencing to it...

Objects are generally stored in heap and can be referrenced by many variables that are in Stack... Here you dont want to hold the reference in the stack of your method... But it is referenced in the stack of LoadIt method by its parameter... Hence the object will not be garbage collected until the Load it method's parameter goes out of scope... In the mean time the LoadIt method can try to reference it again in a global variable or pass it on as a parameter to another method... On a whole, only when all references for a object in stack (or in other objects) goes out of scope, the object is garbage collected...

Getting back the reference to this object, purely depends on what the Load it method does with this object... If the method does nothing other than referencing it with the parameter variable, then you cant get it back... But if the method copies reference to other variable which is available public, then you can use that variable and get the reference back.

like image 172
The King Avatar answered Dec 03 '25 17:12

The King