Private constructor in c#


Private constructor in c# is a special type of function which name same as the class name. If any class having private constructor it means that we can't create the object of that class. Over you if you want to create the object of class which have private constructor then you have to take a default constructor in your class.

Private constructor in c# is a special type of function which name same as the class name. If any class having private constructor it means that we can't create the object of that class. Over you if you want to create the object of class which have private constructor then you have to take a default constructor in your class

(see the real time example of private constructor).

  public class Program
    {
        private Program(int a, int b)
        {
            a = 10;
            b = 11;
        }
        public Program()
        {
       
        }
    }
    class testing
    {
        static void Main(string[] args)
        {
            Program p = new Program();

        }

    }



Classes Which Loads Only one Time In memory. In Singleton Class Constructor Is Always Private and Object Is Always Static.

Imp. Point:

1.In Singleton Class We Have Only One Object Of A Class.
2.Singleton Class Uses Static so it’s Behavior Is Static.

namespace WindowsFormsApplication3
{

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 ob = Class1.Create();
            Class1 ob1=Class1.Create();
            Class1 ob2=Class1.Create();
        }
    }

    public class Class1
    {
        Class1()
        {
        }
        static Class1 ob;

        public static Class1 Create()
        {
            if (ob == null)
            {
                ob = new Class1();
                return ob;
            }
            else
           {
            return ob;
            }
        }
    }
}

Can constructor be private
                                         -Yes

Can a Private Constructor have Parameters ?   
                                                                      -Yes.



Must Read :





Post a Comment

Post a Comment (0)

Previous Post Next Post