Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new objects repeatedly on same variable

Tags:

c#

.net

object

I suppose this is a very silly question but I've been looking around and couldn't find answers on the following questions. Really appreciate answers shedding light on this.

1) What happens to the previous object if instantiating a new one within the same method. Example:

DataTable dataTable = new DataTable();
dataTable = new DataTable(); // Will the previously created object be destroyed and memory freed?

2) Same question as (1) but on static variable. Example:

static private DataView dataView;

private void RefreshGridView()
{
    dataView = new DataView(GetDataTable()); // Will the previously created objects be destroyed and memory freed?
    BindGridView();
}

Thanks!

like image 445
csharp101 Avatar asked Apr 19 '13 16:04

csharp101


1 Answers

// Will the previously created object be destroyed and memory freed?

Potentially. As soon as you do this, you'll no longer be holding a reference to the original DataTable. As long as nothing else references this object, it will become eligible for garbage collection. At some point after that, the GC will run, and collect the object, which will in turn free it's memory.

This is true for static, instance, and local variables. The mechanism is identical in all of these scnearios.

Note that if the object you're referencing implements IDisposable, it's a good practice to call Dispose() on it before losing the reference. Technically, a properly implemented IDisposable implementation will eventually handle things properly, but native resources may be tied up until the GC collection occurs, which may not happen quickly. Note that this has nothing to do with (managed) memory, but is still a good practice.

That being said, your first example is a bad practice. While the memory will (eventually) get cleaned up, you're performing extra allocations that serve no purpose whatsoever, so it'd be better to not "double allocate" the variable.

like image 129
Reed Copsey Avatar answered Oct 07 '22 00:10

Reed Copsey