views:

82

answers:

5

Possible Duplicate:
What is the use of a static class

What are the benefits of declaring a static class?

public static class MyStaticClass
{
}

Are there any other than "it can't be instantiated"?
Why else would you want a static class, for what reasons should a class be static?
Is "any class should be declared as static unless it's meant to be instantiated" a good rule of thumb?

+2  A: 

You need a static class to create extension methods.

hoang
+3  A: 

Static classes are useful as containers for utility functions and constants. If the class does not represent an object and is used only for this purpose then it makes sense to declare it as static.

Sorpigal
A: 

An utility class, which only declares static methods (like System.IO.File) is not ment to be instantiated, so its usually static.

And your right, I find it to be a good use. Singleton is different, as it is meant to be privately instanciated.

Aurélien Ribon
+1  A: 

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

Taken from MSDN directly. It explains it much better than I can. The key fact here is that the object persists throughout the life.

Extention methods also have to be written in static classes. I tend to use these for string extentions, or collection extentions.

jimplode
+1  A: 

If a class has the static modifier then:

  • It makes your intention clear: this isn't just a class which happens to have all static members - it's a class which will only ever have static members
  • You prevent instantiation without needing a private constructor just to suppress the default public one
  • You aren't allowed to declare a variable of that type
  • You aren't allowed to use that type as a type argument (IIRC, anyway)
  • You can declare extension methods in the type if it's a top-level type

The first point is the most important though, IMO. You're communicating intent to both the compiler and other developers.

Jon Skeet