Static classes are automatically sealed, so people can't inherit and override their behavior.
That is the only real difference (unless there is something special in the IL)
So if you use a static class, you save yourself the trouble of making the constructor private, and declaring the class sealed.
I would add, that defining a class as static, is "self-documenting" code. Users of your library will know that this class should not be instantiated, and only has static values.
A static class can never be instantiated. No way, no how.
A non-static class with a private constructor but all static methods can be abused in various ways - inheritance, reflection, call the private constructor in a static factory - to instantiate the class.
If you never want instantiation, I'd go with the static class.
Say you have this utility class:
public class Utility
{
public static string Config1 { get { return "Fourty Two"; } }
public static int Negate(int x) { return -x; }
private Utility() { }
}
If another developer isn't clear on its intent, they could do this:
public class Utility
{
public static string Config1 { get { return "Fourty Two"; } }
public int Config2 { get; set; }
public static int Negate(int x) { return -x; }
private Utility() { }
/// Get an instance of Utility
public static Utility GetUtility()
{
return new Utility();
}
}
Now you have a Frankenstein class. Some of its features require instantiation and some don't. Maybe that's what you want but maybe it's not. You could prevent this with code review, but why not make your intentions explicit in code? Marking the class as
static
eliminates any possible confusion. You can't instantiate a static class or inherit from it.
No comments:
Post a Comment