What are public, private and static constructors and differences between them?

Showing Answers 1 - 12 of 12 Answers

Public constructors are used to instantiate and initialize the fields during object instantiation.

Private constructors are used to restrict the instatiation of object using 'new' operator. This type of constructors are mainly used for creating singleton object.

Static constructors are used when initializing class variables (static variables).

PeterVH

  • Aug 19th, 2011
 

Public constructors = free for all to use
private contructors = If there is danger in the contruction you use a factory pattern or static singleton pattern so that the class can assume responsability and lessen the risks involved
static contructor = Is called once, and in theory you don't know when (well, at least for you make the first instance). Use this for fixed values.

Code
  1.     public partial class Form4 : Form

  2.     {

  3.         public Form4() { InitializeComponent(); }

  4.  

  5.         private void button1_Click(object sender, EventArgs e)

  6.         {

  7.             Debug.WriteLine("Starting the function");

  8.             Debug.WriteLine(Example.MeaningOfLife);

  9.             var toTest = new Example();

  10.             Debug.WriteLine("in my testinstance, IsHiddenInitialized = " + toTest.IsHiddenInitialized());

  11.  

  12.             // guess not, now for the real deal

  13.             var realDeal = Example.GiveInstance("supersecret");

  14.             Debug.WriteLine("in my real deal, IsHiddenInitialized = " + realDeal.IsHiddenInitialized());

  15.  

  16.             /*

  17.              * output =

  18.              * Starting the function

  19.              * Static constructor is called

  20.              * 5

  21.              * in my testinstance, IsHiddenInitialized = False

  22.              * I am a nerd

  23.              * in my real deal, IsHiddenInitialized = True

  24.              * */

  25.         }

  26.     }

  27.  

  28.     public class Example

  29.     {

  30.         public static readonly int MeaningOfLife;

  31.         private readonly TopSecretObject _hidden;

  32.  

  33.         public bool IsHiddenInitialized()

  34.         {

  35.             return _hidden != null;

  36.         }

  37.  

  38.         /// <summary>

  39.         /// Default public contructor for testing purposes

  40.         /// </summary>

  41.         public Example()

  42.         {

  43.             // Setup some harmless test values

  44.         }

  45.  

  46.         /// <summary>

  47.         /// private constructor that does dangerous stuff and should be called only fron inside

  48.         /// this class, where the class itself can make sure nothing goes bad

  49.         /// </summary>

  50.         /// <param name="keepThisHidden">A secret to keep</param>

  51.         private Example(string keepThisHidden)

  52.         {

  53.             _hidden = new TopSecretObject(keepThisHidden);

  54.         }

  55.  

  56.         /// <summary>

  57.         /// Static constructor to make sure the meaning of life is known

  58.         /// </summary>

  59.         static Example()

  60.         {

  61.             MeaningOfLife = 42;

  62.             Debug.WriteLine("Static constructor is called");

  63.         }

  64.  

  65.         public static Example GiveInstance(string secretPassword)

  66.         {

  67.             return secretPassword == "supersecret" ?

  68.                 new Example("I am a nerd") : null;

  69.         }

  70.     }

  71.  

  72.     public class TopSecretObject

  73.     {

  74.         public TopSecretObject(string secretPassword)

  75.         {

  76.             Debug.WriteLine(secretPassword);

  77.         }

  78.     }

  Was this answer useful?  Yes

Constructor are used for creating an object and returning a reference of the object.
so whenever we write
class1 obj=new class1();

Public Constructor
The new Class1() is actually calling a public zero param constructor of class and instance is created.


Private Constructor
And if we mark the constructor as private we wont be able to write
class1 obj=new Class1()
hence the object of class1 cannot be created.
this type of construction is required when we are working with signleton pattern (Design Pattern)

Static Constructor
When we want our static data should be initiallize only one and first time we use
static constructor.
The Static constructor is called only once when the class or any of its derived is loaded in
clr before calling any instance constructor.

  Was this answer useful?  Yes

A public constructor is accessible anywhere in the application
A private constructor is restricted to the class within the application
Static constructor give access to the data without necessarily creating an object class

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions