Whats the best way to kill an object?

  • Thread starter Thread starter moondaddy
  • Start date Start date
M

moondaddy

I'm writing a WPF app in c# and want to know the best way to get rid of an
object. this is how its created

someclass obj = new someclass();
void CreatObjects()
{
aCollection.Add(obj);
AnotherClass obj2=new AnotherClass(obj);
aNotherCollection.Add(obj2);
)

Now I want to completely get rid of this instance of obj and obj2

void KillObjects(obj, obj2)
{
aCollection.Remove(obj);
aNotherCollection.Remove(obj2);
//Since at this moment obj and obj2 are alive in this method, should I set
the to null like this?
obj=null;
obj2=null;
}

What is the most appropriate what to get rid of obj and obj2?

Thanks.
 
moondaddy said:
I'm writing a WPF app in c# and want to know the best way to get rid of an
object. this is how its created

someclass obj = new someclass();
void CreatObjects()
{
aCollection.Add(obj);
AnotherClass obj2=new AnotherClass(obj);
aNotherCollection.Add(obj2);
)

Now I want to completely get rid of this instance of obj and obj2

void KillObjects(obj, obj2)
{
aCollection.Remove(obj);
aNotherCollection.Remove(obj2);
//Since at this moment obj and obj2 are alive in this method, should I set
the to null like this?
obj=null;
obj2=null;
}

What is the most appropriate what to get rid of obj and obj2?

With the code above, you don't need the last two lines of code - after
all, the method's about to end anyway. It doesn't guarantee that
nothing else will have references to the two objects, however, and even
if nothing does, there's no guarantee that the objects will be garbage
collected any time soon.
 
OK thanks.

Jon Skeet said:
With the code above, you don't need the last two lines of code - after
all, the method's about to end anyway. It doesn't guarantee that
nothing else will have references to the two objects, however, and even
if nothing does, there's no guarantee that the objects will be garbage
collected any time soon.
 
Back
Top