Disposing of a static object

  • Thread starter Thread starter Claire
  • Start date Start date
C

Claire

Ive a static instance of an object in a class. It needs to be Dispose(d) of
when it's finished with.
How do I do this? Or don't I have to worry about it?


Class myClass
{
private static TMyClass myClass = null;

public static bool ClassConnected
{
if (myClass == null) myClass = new(TMyClass);
return myClass.Connected;
}
}
 
Claire,

If you disposed of the instance myClass, then you would have to create a
new instance every time the ClassConnected property is called.

The lifetime of the object assigned to myClass is up to you, but
generally, I don't think that getting rid of the static instance is going to
do you any good.

What is it that you are trying to do exactly?

BTW, the line

if (myClass == null) myClass = new(TMyClass);

Is incorrect, it should be:

if (myClass == null) myClass = new TMyClass();

Assuming it has a parameterless constructor.
 
Hi Nicholas
Pardon my poor pseudocode, I noticed that after I posted.
I can't find the real code now, but it worried me in a general hunt for
memory leaks/efficiency whether I should worry about disposal of static live
instances
(memory profilers are difficult to understand at first)
 
Claire said:
Ive a static instance of an object in a class. It needs to be Dispose(d) of
when it's finished with.

Invoke Dispose() on it when you are done using it :)

Is your problem that it's unclear when that is? If this is the case, you
probably can't get by with having a static instace.
How do I do this? Or don't I have to worry about it?

Doesn't "needs to be Dispose(d) of", mean that you have to worry about it?

You don't need to Dispose object just for the sake of memory or closing
files, although you need to Flush() streams if the aren't closed or
disposed.
 
Back
Top