Is there anything like *static destructor*?

  • Thread starter Thread starter Morgan Cheng
  • Start date Start date
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#?
 
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.
 
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#?
 
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
 
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
 
Back
Top