0

Im newer to C# and can't seem to find a direct answer to this:

So in a method I create an object reference to read an xml doc:

XElement xFinancialBill = xDoc.Root.Element("Financial_Transaction").Element("Bill");

It does some processing with the object and the method ends, but my question is: do I need to null out the above object reference (eg. xFinancialBill = null;) before the method ends for garbage collection/freeing up memory to work correctly?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
EldritchText
  • 121
  • 1
  • 2
  • 7
  • No, the garbage collector will take care of it once the variable is out of scope and is not referenced anywhere else. – juharr Dec 18 '18 at 17:29

2 Answers2

0

No. The garbage collector will free all objects that are not reachable any more and local variables of a method that has finished are in this category (provided you did not have additional references e.g. because you returned the value or stored it in a member field etc.

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
0

Generally you don't need to worry about object references once they have gone out of scope - the garbage collector will clear up.

However, if you are using an object whose class implements the IDisposable interface then you need to make sure that it disposes of any unmanaged resources by either explicitly calling the IDisposable.Dispose() method or by wrapping its usage in a using block.

Look up IDisposable in the MSDN for further explanation.

spodger
  • 1,668
  • 1
  • 12
  • 16