destructing static member variables

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

This is a C# question. If this is not the right place to for this question,
Please point me to a different news group.

Are there any static destructors in C#? I found there is no such concept. In
that case, How can one destruct the static member variables intialized in
static constructor? Is there any work around?
 
Venkat said:
This is a C# question. If this is not the right place to for this
question,
Please point me to a different news group.

Are there any static destructors in C#? I found there is no such concept.
In
that case, How can one destruct the static member variables intialized in
static constructor? Is there any work around?

The object which you assign to a static variable will be garbage collected
when the AppDomain is unloaded. If any cleanup is required, you can give
that type a finalizer. As a trick you can assign a finalizable type to a
static readonly variable to act as a "static finanalizer".

class Foo
{
class StaticFinalizer
{
~StaticFinalizer()
{
//Foo's cleanup code here
}
}
static readonly StaticFinalizer staticFinalizer = new StaticFinalizer();

. . .
}

The StaticFinalizer instance will stay alive until the AppDomain is
unloaded. Subsequently it will be collected and the finalizer should run.
NB there are exceptional situations in process shutdown where pending
finalizers will not be run.

David
 
Back
Top