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.
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()
{
Console.WriteLine("ClassA::Constructor()");
}
public ClassA(int a)
{
Console.WriteLine("ClassA with
params::Constructor()");
}
}
class Test
{
static void Main(string[] args)
{
ClassA a = new ClassA(10);
Console.ReadLine();
}
}
}
Constructor Interview Questions and Answers
2.We know that Base class constructor called first. But if we creating object with parameters, and base class have both constructor default and parameter,then which constructor of base class called first.
3.How to call base class parameterized constructor first in c#?
4.What is the difference between constant, readonly and static keywords in C#?
3.How to call base class parameterized constructor first in c#?
4.What is the difference between constant, readonly and static keywords in C#?