Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Private constructor

Private constructor: Private constructor is a special instance constructor with "private" access modifier in a class.

It is generally used in classes that contain static members only.

Syntax:

[Private Access Modifier] ClassName()
{
 ..
}

 

Points to remember:

A class with private constructor cannot be inherited.
You cannot create an object of the class which has private constructor only.
You can create instance of class if class contain public constructor along with private constructor.
You can use only parameterized constructor with private constructor.


Example:

class Program
    {
 
        static void Main(string[] args)
        {
            studentPrivate.InstituteName = "PLGP";
            var ITStudent = new studentPrivate("Shivaji");
            ITStudent.StudentName = "Nagnath";
            var ElectronicsStudent = new studentPrivate("Shivaji");
            ElectronicsStudent.StudentName = "Girish";
           
            ITStudent.DisplayStudentDetails();
            ElectronicsStudent.DisplayStudentDetails();
 
        }
   }
 


public class studentPrivate
    {
        public static string InstituteName;
        public string StudentName { get; set; }
        public string TeacherName;
 
     
        public studentPrivate(string teacher)
        {
            TeacherName = teacher;
        }
        //private Constructor
        private studentPrivate()
        {
            InstituteName="JNEC";
        }
 
        public void DisplayStudentDetails()
        {
            Console.WriteLine("Institute Namne: {0}", InstituteName);
            Console.WriteLine("Student Name: {0}", StudentName);
            Console.WriteLine("Teacher Namne: {0}", TeacherName);
        }
    }
 


Output:


 

Invalid entry,please enter valid data.

Loading