destructing static member variables

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?
 
D

David Browne

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top