Tinkering with C# I've found that you can create a new instance without storing it inside some identifier.
I understand that these declarations only work with classes because of the need to call some method within them, but does this instance always remain in memory?
Example, suppose I have the following class:
class Printer
{
private string _internal;
public void Print() { Console.WriteLine(_internal); }
public Printer(string s) { _internal = s; }
}
And I call from:
static void Main()
{
new Printer("Hola Mundo!").Print(); // Imprime "Hola Mundo"
}
Will the object of type Printer
that was instantiated always remain in memory until the end of the execution of the program?
The instances of the objects have a scope in which they are accessible, in this case the instance of
Printer
is the Main() method when you leave it the instance is available to be collected by the Garbage Collector (GC)If you want to ensure an effective destruction of the object use the block
using
Variables have a scope in which they can be used, when you exit the scope the GC can collect them and free the memory, but this is automatic for you.
Yes, the instantiated Printer object will always remain in memory and will be removed from memory when Printer 's destructor is called , usually when program execution ends.
I think a static class would be good for your implementation ;)