Share via


Static classes, destructor or dispose?

Question

Wednesday, March 15, 2006 5:57 PM

Hi, I just have a few questions concerning static classes.

A static class seems to create itself as soon as one of its static methods are called. What i'm wondering is when do static classes clean themselves from memory and can you specify a destructor when it does clear itself from memory?

I'm using a static class for my datalayer, and I want to make sure to dispose of any lingering connections before the class exits.

 

-Watson

All replies (3)

Thursday, March 16, 2006 12:45 AM âś…Answered

A static class is a class which is in theory really not instantiated at all, it exist in the "class" space, not the "instance" space.  To make a class static is just a way to state that all methods and fields MUST be static.  In a normal class, the members works on the instance objects, whereas a static method works on the class itself.

In .net it is constructed/instantiated  the first time it's loaded - often when any member is accessed.  However, you have no control on when this really is happening - it is not guaranteed.  You should regard the static class as always instantiated - to get the least trouble.

It is therefore never released, it doesn't have any destructors, and is not involved in garbage collection. 

If your static class hold onto external resources, you should free them explicitly by calling another static method to this.


Thursday, March 16, 2006 6:08 PM

Some good insight.

"It is therefore never released"

Seems to me that the static class will need to be released when the application closes.

On another note, what is your take on the data access layer as far as making it a static or non static class?


Thursday, March 16, 2006 8:19 PM

Yes, when the application dies, the static dies too, so the word "never" is just in the context of the lifetime of the application.

I would make the data access layer non-static, so that I have the possibility to use interfaces to decouple them, if I need to.  I normally never use statics, but in the case of a DAL, you surely have that option. The cost of having a DAL non-static is near nil, since it so lightweight.   I normally construct the DAL object within the constructor of the business object.  The business object aggregates a DTO (Data Transfer Object), which the DAL operates on.   This works very well aspecially for distributed systems, because the DAL is separated from the DTO, thus the DTO can be transferred onto f.e. a smartclient application.  

As an application grows, you may need to decouple things, and then I would not like to have statics around. 

Also, take a look in Martin Fowler's Patterns of Enterprise Application Architecture - he has some good thinking there