I have a class with only static methods. Should the class itself be made static too? Does it matter?
2 Answers
Does it matter?
Making a class static ensures that it can never be instantiated by generating a compiler error should the user attempt to do so. If the class, consisting of only static members, is simply not intended to be instantiated, there is no reason not to make it static. You can choose not to do so, but instances of such a class aren't going to be very useful, and users creating these instances are going to be left quite confused.
On the other hand, if you intend for instances of this class to be created but you expect derived classes to implement their own instance members, chances are that this class should be abstract, rather than static (and perhaps those instance members should be stated upfront via abstract definitions or an interface).
In general: Yes.
You can prevent the programmer to create object instances of a certain class by making the class static
. If this is what you intend, then do it. This prevents mistakes, by showing (other collegues, etc.) that the class is not intended to be instantiated.
public static class A
{
// Some static member
}
A a = new A(); // Compilation error
new YourClass()
.YourClass
doesn't have to bestatic
to doYourClass.doSomething();
. OnlydoSomething()
has to bestatic
.static
is to take advantage ofusing static
so you don't have to qualify the methods with the class name in C# 6.