Reputation: 153
Let's say that I create an object:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CreateObjOnobj
{
class Program
{
static void Main(string[] args)
{
testcreate myobjecttotest;
myobjecttotest = new testcreate();
myobjecttotest.num = 20;
myobjecttotest.bill = true;
myobjecttotest = new testcreate();
Console.WriteLine(myobjecttotest.bill.ToString());
Console.ReadKey();
}
}
class testcreate
{
public int num = 0;
public bool bill = false;
}
}
Does this code delete the object automatically and create a new one without loss in memory??
Thanks
Upvotes: 1
Views: 945
Reputation: 2978
Yes it will be automatically garbage collected, unless there are another instance pointing to that object.
For example :
We created another instance of testcreate
that will be assigned with the pointer value of the first instance.
testcreate myobjecttotest = new testcreate();
testcreate myobjecttotest2 = myobjecttotest;
So if we reinstantiate myobjecttotest = new testcreate()
The previous object will not be deleted since myobjecttotest2
is currently pointing to it
Upvotes: 1
Reputation: 37000
Basically yes but in more detail no.
When you re-assign a variable the reference to the previos object gets lost. However the instance itself still exists as long as Garbage Collector does not kick it. Anyway you won´t care much about that as long as no unmanaged references are handled - e.g. COM-objects which you have to release in some way. So the same happens as when you create an instance of a class and "leave" the scope of that variable:
void MyMethod()
{
var myVar new MyClass();
}
When you leave the method the variable and therefor all references to your instance of MyClass
get deleted and thus are marked for garbage-collection. However you don´t know when this will happen.
Upvotes: 2
Reputation: 8498
Not exactly.
What actually happens is that you change variable that pointed to the first object, and now it points to the second object. From that moment on, no one points to the first object any longer.
Since .NET is equipped with automatic memory management, the garbage collector periodically checks for objects with no "roots" -- those no one holds a reference to. It removes such "orphan" objects from memory.
BUT -- you can make no assumptions about when the garbage collection will occur. It will occur sometimes later, that's all you know.
In general, when you create a second object and change the variable to point to the second object, you end up with two objects in memory. Sometimes later, the first object will be removed by the garbage collector.
Upvotes: 6