Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

benefits of a static class [duplicate]

Tags:

c#

static

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?

like image 637
bevacqua Avatar asked Oct 27 '10 14:10

bevacqua


3 Answers

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.

like image 194
Jon Skeet Avatar answered Oct 18 '22 14:10

Jon Skeet


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.

like image 24
sorpigal Avatar answered Oct 18 '22 13:10

sorpigal


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.

like image 31
jimplode Avatar answered Oct 18 '22 14:10

jimplode