Tuesday, May 11, 2021

C# Private Constructor

Private Constructor: A non-static constructor, also called instance constructor, has access modifier (e.g. public, private). Private constructor is an instance constructor which has 'private' access modifier and private constructor is used to prevent the instantiation of its class in another class. This is explained by considering two different cases. In first case, private constructor is not used to show why it can be required. In second case, private constructor is used to meet the requirement

Case 1 A class with only static fields can be instantiated as shown below in Example1. It means that the object of such class can be created but creating object for such class is not needed as its all fields are static. To prevent creating objects for such class, we use private constructor, which is shown in case2.

Example1
using System;
namespace ConsolePrivateConstructor
{
    class Test
    {
        static int s; //only static field
        static Test() //static constructor
        {
            Console.WriteLine("Static");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test(); // default constructor invoked 
            Console.ReadKey();
        }
    }
}
OUTPUT
Static


Case 2: A class with only static fields can be instantiated as shown in the above  Example1. To prevent creating objects for such class, we use private constructor as shown in Example2,

Example2
using System;
namespace ConsolePrivateConstructor
{
    class Test
    {
        static int s;
        static Test()
        {
            Console.WriteLine("Static");
        }
        private Test()
        {
            //no code, private constructor to prevent creation of object in another class
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test(); // illegal, constructor cannot be invoked 
            Console.ReadKey();
        }
    }
}


No comments:

Post a Comment

Hot Topics