简体   繁体   中英

Static Class Vs. Class with private constructor and all static properties and methods?

When I create utility classes I typically create a class that has a private constructor and exposes all of it's methods and properties as static. What's the best approach for this? What's the difference between the way I do or creating a static class?

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.


Edit - Clarification for FosterZ's comment

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.

In addition to the previous answers: The compiler won't allow non-static members on static classes and produces and error. This may help a little bit to not accidently add non-static members.

you can pass object of a class that has private constructor as a parameter to any method but you can't do the same with static class. This is the major difference.

Also I'm going to go with the private constructor never being called by the static methods. So any initialisation in there would be wasted... But that's just a theory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM