Whats the best way to kill an object?

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.
 
J

Jon Skeet [C# MVP]

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.
 
M

moondaddy

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top