开发者

benefits of a static class [duplicate]

This question already has answers here: Closed 12 years ago.

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?

I开发者_高级运维s "any class should be declared as static unless it's meant to be instantiated" a good rule of thumb?


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.


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.


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.


You need a static class to create extension methods.


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜