FPGA
FPGA

Reputation: 3865

Doing something whenever an object gets disposed

Consider the following class :

public class SomeObject
{
        public string x { get; set; }
        public int y { get; set; }

        private void Serialize(){}
        //When the object gets collected by the GC want to call the Serialize() function
}

What event should I use for that purpose?

I want to call the function when the GC collects the object or when the application closes, but I want to do it from inside the class

Upvotes: 0

Views: 86

Answers (3)

Guffa
Guffa

Reputation: 700432

If you really, really, need to do something when the object is collected, then you would use the Finalize method.

Normally the Finalizer method is only used as a backup for when objects are not disposed properly, to try to wipe up most of the mess.

There is no guarantee that the Finalizer method is actually executed for all objects, so it's not a reliable way to clean up objects. When the application ends, the garbage collector spends some time to collect objects and run Finalize methots for those that implement it, but if that process takes too long, it will just abandon the rest of the objects and let the application close.

An object that needs to do something when it's not used any more, should implement the IDisposable interface. Note however that it doesn't mean that the object will do anything automatically, it's the responsibility of the programmer using the object to dispose of it correctly.

Upvotes: 4

icbytes
icbytes

Reputation: 1851

Public override OnDispose. But Your class must implement IDisposable for this.

Upvotes: 0

Cyclonecode
Cyclonecode

Reputation: 30061

Could you not call the Serialize() method in the destructor:

public class SomeObject
{
    public string x { get; set; }
    public int y { get; set; }

    private void Serialize(){}

    ~SomeObject() {
      Serialize();
    }

}

Upvotes: 2

Related Questions