Question

Person p = new Person("Bob", 10);
p = new Person("James", 20);

Turns out I am loosing a reference to an instance containing "Bob". If I don't want to rely on c#'s GC, how can I personally delete this instance before re-assigning p to point towards James? Just to avoid extra garbage.

Was it helpful?

Solution 2

You could reuse the instance, instead of replacing it:

Person p = new Person("Bob", 10);

p.Name = "James";
p.Number = 20;

That way there is no Bob instance that you loose Reference to.

However, for code readability and to avoid potential bugs you should not reuse variables in that way.

OTHER TIPS

You can't. You can only ask GC to perform collection, but there is no way to say it will actually take your object (neither you can ask GC to collect just one object).

GC.Collect Method

Forces an immediate garbage collection of all generations.

And you shouldn't do that unless you have very good reason (looks like you don't).

It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues.

Taken from here: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top