In this .NET interview
questions we will focus on constructor
Can we declare constructor with private modifier?
Yes.
What will happen then?
When any class contain private constructor,
- We cannot instantiate its objects. In simple words we cannot write MyClass m=new MyClass();
- We cannot inherit any class from it.
Why we need it then?
Many times in our application we will have some classes which are going to be used again and again and thus we creates objects of them again and again. Example is “find box in our notepad” or may be “exception logger in our application”. Now in order to reduce the object creation overhead from processor we will create object of that class once and reuse across. For that first thing we have to do is take away the object creation power from the end developer. We will achieve this by making our constructor private.
Where we implement private constructors normally?
It is implemented while using singleton pattern.
Can you show a small example?
Following is the code snippet: -
Public
class SingletonClass
{
privateSingletonClass();
staticSingletonClassobjCurrent=new
SingletonClass();
public
static SingletonClassGetObject()
{
returnobjCurrent;
}
}
//end
developer code
SingletonClass
o=SingletonClass.GetObject();
For Design Pattern and other online technical trainings visit
www.sukesh-Marla.com
or contact
SukeshMarla@Gmail.com
Also see following .NET
interview questions video on use of private constructor: -