Is there anything like *static destructor*?

M

Morgan Cheng

In C#, we can initialize static member variables in static constructor.
Now, when to destruct these static member variables? If these variables
hold external reference(e.g. log file stream), it is supposed to be
disposed in *static destructor*. However, there is no so-called *static
destructor*. Is there any substitue of *static destructor* or *static
dispose* in C#?
 
N

Nicholas Paldino [.NET/C# MVP]

Morgan,

No, there isn't. The closest thing you can do is set an event handler
to the DomainUnloaded event on the AppDomain and perform your cleanup there.

Hope this helps.
 
M

Morgan Cheng

Nicholas said:
Morgan,

No, there isn't. The closest thing you can do is set an event handler
to the DomainUnloaded event on the AppDomain and perform your cleanup there.

Hope this helps.

Thanks, it really helps.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Morgan Cheng said:
In C#, we can initialize static member variables in static constructor.
Now, when to destruct these static member variables? If these variables
hold external reference(e.g. log file stream), it is supposed to be
disposed in *static destructor*. However, there is no so-called *static
destructor*. Is there any substitue of *static destructor* or *static
dispose* in C#?
 
B

Brian Gideon

Morgan,

There is no static destructor because you cannot finalize or destruct
something that hasn't been instantiated. You may be confused because
we typically call static class initializers constructors in C# which I
think is a bit of a misnomer. If your static references are objects
that override Finalize then their destructors will be called when the
application ends. That's usually sufficient, especially in the case of
a file stream. If you need more control then call a static method on
the class just before your application ends.

Brian
 
S

SP

Morgan Cheng said:
In C#, we can initialize static member variables in static constructor.
Now, when to destruct these static member variables? If these variables
hold external reference(e.g. log file stream), it is supposed to be
disposed in *static destructor*. However, there is no so-called *static
destructor*. Is there any substitue of *static destructor* or *static
dispose* in C#?

If you use a singleton pattern instead then you can "nullify" the instance.
This is commonly done when doing unit testing and singletons are involved.

PS
 

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