I’m trying to decide if this StreamWriter variable should be declared as a field, a local, or as a local inside the if statement. My worry is that after I pass it to Console.SetOut() and execution continue past the if statement there will be no more references left to this object and it will get Garbage Collected.
Am I overthinking this or is it safe to assume that the Console class will reference it throughout the execution of my application?
The GC
countswill track references even if they’ve been passed around the application. The GC should only collect objects if you have no way to access them any more.Specifically,
Console.SetOutkeeps an internal reference to theTextWriterpassed to it.