Static classes: no more private constructors
What is it?
With version 1 of C#, the only way to prevent a class that contained only static members from being instantiated was to give it a private constructor. This was a hack: it was effective, but messy. Version 2 fixed that by allowing classes to be marked as static.
Which C# version supports it?
Version 2 and above.
Why use it?
If you have a class that only contains static methods, it makes no sense for a developer to create an instance of that class. By marking it static, you both reassure the developer that the class only contains static methods, and you prevent said developer pointlessly instantiating an instance of your class.
Static classes are handy for situations where you have data that needs to have global scope, or for methods that are self-contained or stateless.
How to use it
The following code snippet shows a contrived, and rather pointless, static class:
public static class ClassStatic
{
private static int field1;
static ClassStatic()
{
field1 = 1;
}
static int Field1
{
get { return field1; }
}
static int GetField1()
{
return field1;
}
}
A static class can have a static constructor, as well as static properties, fields and methods.
No comments yet. Be the first.
Leave a reply
