Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




.NET interview questions: - All about Constructor

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,

  1. We cannot instantiate its objects. In simple words we cannot write MyClass m=new MyClass();
  2. 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: -

Helpful Website Url
http://www.questpond.com/
Share this article   |    Print    |    Article read by 5574 times
Author:
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site http://www.questpond.com for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers
Related Articles:
Related Interview Questions: