Do these types of expressions always remain in memory?

4

By moving with C # I have found that a new instance can be created without storing it inside an identifier.

I understand that these statements only work with classes because of the need to invoke 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"
}

The type object Printer that was instantiated will always remain in memory until the execution of the program ends?

    
asked by NaCl 03.05.2016 в 14:41
source

2 answers

4

The instances of the objects have a scope in which they are accessible, in this case the instance of the 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

static void Main()
{
    using(Printer printer = new Printer("Hola Mundo!"))
    {
        printer.Print();
    }
}

The variables have an area in which they can be used, when you leave them the GC can collect them and free the memory, but this is automatic for you.

    
answered by 03.05.2016 / 15:28
source
0

Yes, the object of type Printer instantiated will always remain in memory and will be removed from it when the destructor of Printer is invoked, generally when the execution of the Program.

I think a static class would be good for your implementation;)

    
answered by 03.05.2016 в 15:10