0

How can i delete object even it has references(c# or Java)?

For example:

void Main()
{
    var f = new Foo();
    var person = f.GetPerson();

}

public class Foo
{
    private object _person;

    public Foo()
    {
        _person = new object();
    }

    public object GetPerson()
    {  
         return _person;
    }
}

I want to delete _person from memory how can i do it?

Neir0
  • 12,849
  • 28
  • 83
  • 139

3 Answers3

11

You can't, briefly.

If you did want to achieve something similar, you could reference your Person via a proxy, and pass the proxy around. So you could set the underlying Person reference to null (simply indicating the object is available for removal - not forcing its removal), but the clients would still contain a proxy reference.

You may want to check out Java SoftReferences and WeakReferences, which are related, and can trash objects during garbage collection cycles, despite their weak/soft references being available elsewhere.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

You can't remove an object from memory with reference in a managed language.

You can remove it from memory in C# by setting the reference to Null and calling GC.Collect()

Will Calderwood
  • 4,393
  • 3
  • 39
  • 64
1

Basically, you want to invalidate a living reference. This would break the key assumption of languages with automatic memory management, which is the impossibility of derefencing invalid pointers. At least in Java this is surely impossible and I invite a C# expert to contribute to this community wiki with C#-specific information.

Towards the solution of your requirement: you must encapsulate the reference to your object inside another one and never let the reference escape, so as to ensure 100% ownership of that reference. So the outside object will need to have the complete API of the inside object replicated, basically the Decorator pattern.

If you do that, you'll have the option to set the internal reference to null at any time and thus reliably release the object.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436