Using static class to separate data and behavior independent of any object

Hi

A few days back I was having a conversation with my colleague on the use of static class. At that point I decided to write a post on the issue giving an example on when to use a static class and members.

We use static class when we have to separate data and behavior that will be independent of any object identity. The data and functions do not change regardless of what happens to the object.

A static class can only contain static members. We cannot create an instance of a static class. Static class is always sealed and they cannot contain instance constructor. Hence we can also say that creating a static class is nearly same as creating a class with only static members and a private constructor (private constructor prevents the class from being instantiated).

The advantage of using the static class is that compiler can check that no instance of the class is accidentally added. The complier will not allow any instance class of a static class. We also cannot inherit a static class since it is sealed. Static class do not have constructor, but can still declare static constructor to set up the initial values.

Static class also makes the implementation simpler and faster since we do not have make and instance of the class to call its method.  An example of good use of static class would be a class like math, which does all the mathematic function, or a currency converter class to convert currency class for converting the currency.

Hope this helps
Thanks
Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 8/6/2008 9:30:58 AM

we use singlenton static generic lists with custom objects with no static members.
we actually use as if they were application values.
so when the web app starts we create the lists and keep referencing across the site.
we use them for url rewriting, in a BasePage, file references and even for internal url references.
What woudl you say to that!!!?

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia