Private vs Static constructors in .Net

人走茶凉 提交于 2019-12-03 06:28:23

Static constructors: used for initialising static members.

Private constructors: used when you only want a class to be instantiated from within its own code (typically in a static method). For example:

public class Thing
{
    static int Number;

    static Thing()
    {
        Number = 42; // This will only be called once, no matter how many instances of the class are created
    }

    // This method is the only means for external code to get a new Thing
    public static Thing GetNewThing()
    {
        return new Thing();
    }

    // This constructor can only be called from within the class.
    private Thing()
    {
    }
}

When should I use a private constructor in my class?

When you want a constructor, but don't want to expose it to the world. This could be because you have a factory method that calls the constructor (after validation), or because that constructor is called by ctor-chaining (i.e. public Foo(string) : this() { ...}).

Additionally, note that reflection code is often able to use a private constructor - for example serialization or ORM libraries.

Also, in early C# compilers, when you are writing what would now be a static class - having a private constructor was the only way of making it appear uncreatable.

When should I use a static constructor in my class?

When you need to initialize some static state prior to that state being accessed by instances or static methods.

Static constructor is used to intialize the static members of the class and is called when the first instance of the class is created or a static member is accessed for the first time.

Private constructor is used if you have overloads of the constructor, and some of them should only be used by the other constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!