python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
Angular 2 Interview Questions and Answers

Best Use of C# Private Constructors [How To?]

What do we need of private constructor in C#?
1.A private constructor means that the class can't be instantiated from outside the class.
2.Private constructors can be useful when using a factory pattern.
3.You cannot add public constructor without parameters. i.e.

4.If the class ONLY has private constructors, it cannot be instantiated from outside.

5.When you want to prevent the users of your class from instantiating the class directly.
6.A static method can call the private constructor to create a new instance of that class.
7.In this case, you have a static method defined inside the class that internally calls the private constructor. i.e.
class A
private A() { }
private static A theA = new A();
public static A getAInstance() { return theA; }

8.If you want to create object of class(ClassA) even if we have private constructor(ClassA) then we need to add a public parameterise constructor along with private constructor. i.e.

             namespace ConsoleNamespace
                class ClassA
                    private ClassA()

                    public ClassA(int a)
                        Console.WriteLine("ClassA with params::Constructor()");
                 class Test
                    static void Main(string[] args)
                        ClassA a = new ClassA(10);

Constructor Interview Questions and Answers


Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions