What is the need of private constructor in C#?

前端 未结 12 1557
鱼传尺愫
鱼传尺愫 2020-12-13 21:32

What is the need of private constructor in C#? I got it as a question for a C# test.

12条回答
  •  没有蜡笔的小新
    2020-12-13 21:57

    Basically you use private constructors when you are following a singleton design pattern. In this case, you have a static method defined inside the class that internally calls the private constructor.

    So to create the instance of the class for the first time, the user calls the classname.static_method_name. In this method, since the class's object doesn't yet exist, the static method internally calls the private constructor and returns the class's instance.

    If the class's instance already exists, then the static method simply returns the instance to the calling method.

提交回复
热议问题