jnovacho jnovacho - 2 months ago 13
C# Question

Is it possible for instance to destroy/delete self?

NOTE: I'm interested in C#,Java and C++ most, but as this is the more academic question any language will do.

I know that this problem is solvable from outside, by using appropriate methods of given languages (calling

free
,
Dispose
, or by removing all references to instance).

My idea is that I create an instance, and in the constructor , I start the private timer. When the timer ends it will call some instance method and destroy the variable.

I think that in C# it should be possible to call
Dispose
on self, when the
IDisposable
is implemented, but this would not destroy the instace.

In C++ I could call the
destructor
, but that would lead to the memory leak, plus it is really bad practice.

In Java I have no clue, assigning to
this
it's not possible as it is
final
field.

So is there any way for instance, to destroy self?

Answer

Your question is very interesting, and I don't know of any other way to do so in C# but to force from the inside of the instance its destruction from the outside. So this is what I came up with to check if it is possible. You can create the class Foo, which has event that is fired when the specific interval of the timer elapses. The class that is registered to that event (Bar) within event de-registers the event and sets the reference of the instance to null. This is how I would do it, tested and it works.

public class Foo
{
    public delegate void SelfDestroyer(object sender, EventArgs ea);

    public event SelfDestroyer DestroyMe;

    Timer t;

    public Foo()
    {
        t = new Timer();
        t.Interval = 2000;
        t.Tick += t_Tick;
        t.Start();
    }

    void t_Tick(object sender, EventArgs e)
    {
        OnDestroyMe();
    }

    public void OnDestroyMe()
    {
        SelfDestroyer temp = DestroyMe;
        if (temp != null)
        {
            temp(this, new EventArgs());
        }
    }
}

public class Bar
{
    Foo foo;
    public Bar()
    {
        foo = new Foo();
        foo.DestroyMe += foo_DestroyMe;
    }

    void foo_DestroyMe(object sender, EventArgs ea)
    {
        foo.DestroyMe -= foo_DestroyMe;
        foo = null;
    }
}

And in order to test this, you can set up a button click within a Form, something like this, and check it in the debugger:

Bar bar = null;
private void button2_Click(object sender, EventArgs e)
{
       if(bar==null)
             bar = new Bar();
}

So next time when you click the button, you will be able to see that Bar instance still exists but the Foo instance within it is null although it has been created within the Bar's constructor.

Comments