Moslem Ben Dhaou
Moslem Ben Dhaou

Reputation: 7005

The .NET Garbage collector

This is a very basic question. I am debugging some memory leaks and got totally confused. Suppose I have the following:

public class ObjectData : IDataObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ObjectRepository<T> where T : IDataObject
{
    private Dictionary<int, T> Objects;

    public ObjectRepository()
    {
        Objects = new Dictionary<int, T>();
        // load Data
    }

    public T GetDataObject(int id);
    {
        return Objects[id];
    }

    public Reset()
    {
        Objects = new Dictionary<int, T>();;
    }
}

Now suppose I have the following program flow:

public Main()
{
    var DataRepository = new ObjectRepository<ObjectData>();

    // Constructor called and Data loaded

    var myObject = DataRepository.GetDataObject(1);

    DataRepository.Reset();

    // Call manually the garbage collector or leave it

    // Program flow continue after this
}

The question is, will the garbage collector get rid of the collection initially created by the constructor? Or it will not because one of the elements is still referenced in the program flow (myObject)?

Upvotes: 2

Views: 96

Answers (3)

dcastro
dcastro

Reputation: 68750

After your call to Reset, there is no strong references to your initial dictionary. Thus, it will be elected for garbage collection.

Or it will not because one of the elements is still referenced in the program flow (myObject)?

It doesn't matter which objects the dictionary refers to, what matters is who refers to the dictionary. In this case, no one. It's perfectly possible for the dictionary to be collected while its contents are still alive.

Upvotes: 1

usr
usr

Reputation: 171246

To answer such questions ask yourself: Who is referencing the object in question (in this case the overwritten dictionary)?

DataRepository is not. You overwrote the object reference pointing to the old dictionary.

myObject is not because ObjectData does not have any field of type dictionary. It can't reference a dictionary.

Nobody is left to reference the old dictionary.

Upvotes: 1

Chris
Chris

Reputation: 5514

It will be collected (eventually), since there is no more references to it. Getting a reference to something in a dictionary doesn't give you any reference to the dictionary itself! Unless that object somehow references the dictionary internally, that is.

Upvotes: 1

Related Questions