Saturday, 16 August 2014

Private constructor


1.       If constructor of classis defined private then object of that class cannot be instantiated externally  only class itself can insatiate the object of same class
2.       The only way to create an instance of the class is by calling a static method within the class which creates an instance, or returns a reference to an existing instance.
3.       Generally, they are used in singleton design patterns, where the code ensures that only one instance of a class can ever be created
4.       In below example , user can not instantiate the object of class PrivateConstrctorSample
5.       User has to call CreatePrivateConstrctorSample static method to insatiate the object of the class



public class PrivateConstrctorSample
    {

        private PrivateConstrctorSample()
        {

        }

        void SampleMethod()
        {
           
        }

        public static PrivateConstrctorSample CreatePrivateConstrctorSample ()
        {
            return new PrivateConstrctorSample();
        }


    }

No comments:

Post a Comment