C#

Private and Static Constructors in C#

This article describes Private and Static Constructors in C#. In general, a class has all of its constructors declared as public. While declaring the constructors of a class as public ensures that we can create its objects, sometimes we don’t require it. In other words, if we need to create a class in such a way that it should not be possible to instantiate it. So, we can do it by making its constructors private. However, still we can use the functionality of that class. In order to do so, we can create a method within the class that returns an instance of it. Also, we must declare that method as static. Because now we can’t have any instance of that class before that static method executes.

When Should We Use Private Constructors in a Class?

In case, a class contains only static methods, we must ensure that its instances should not exist. In this case, we either declare a constructor without an access modifier or explicitly declare the constructor as private. Hence, we can prevent that class to have instances. Since a class containing only static methods doesn’t exhibit a specific behavior. So we can avoid making its objects.

Static Constructors

Basically, a static constructor initializes the static fields of a class.

Programs to Demonstrate the Private and Static Constructors in C#

The following program demonstrates the use of private constructors. Since the class FactorialFunctions contains only two static methods, it has a private constructor. Therefore, we can’t instantiate this class. In order to call the methods, we just need the class name and dot operator. Furthermore, the class named MyClass contains a constructor without any access modifier. Also, class A contains a constructor explicitly declared as private.

using System;
namespace PrivateConstructorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
           // FactorialFunctions ob = new FactorialFunctions();
            Console.WriteLine("Factorial of 6 = "+FactorialFunctions.Factorial(6));
            Console.WriteLine("Factorial of 9 = " + FactorialFunctions.RecursiveFactorial(9));
       
        }
    }
    class FactorialFunctions
    {
        FactorialFunctions() { }
        public static int Factorial(int v)
        {
            int fact = 1;
            if (v == 0) return 1;
            for (int i = 1; i <= v; i++)
            {
                fact = fact * i;
            }
            return fact;
        }

        public static int RecursiveFactorial(int v)
        {
            if (v == 0)
                return 1;
            else
                return v * RecursiveFactorial(v - 1);
        }
    }


    class MyClass
    {
        MyClass() { }
    }
    class A
    {
        private A() { }
        static void myfunction()
        { }
    }
}

Output

Using Private Constructor in a Class
Using Private Constructor in a Class

The following program demonstrates the use of a static constructor. While using a static constructor we must remember certain important points about it. Firstly, when the program executes, the static constructor runs first. Also, the static constructor executes only once. Further, a static constructor can’t take any argument. Therefore it can’t be overloaded. Also, it should not use any access modifier and can’t be inherited either.

using System;
namespace StaticConstructorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Resident ob = new Resident();
            Console.WriteLine(ob);
            Resident ob1 = new Resident();
            Console.WriteLine(ob1);
            Resident ob2 = new Resident("Vikas", 20);
            Console.WriteLine(ob2);
        }
    }
    class Resident
    {
        static int societyID;
        string name;
        int age;
        static Resident()
        {
            societyID = 100;
            Console.WriteLine("Inside Static Constructor");
        }
        public Resident()
        {
            name = "Resident"; age = 1;
            Console.WriteLine("Inside Default Constructor");
        }
        public Resident(string name, int age)
        {
            this.name = name;
            this.age = age;
            Console.WriteLine("Inside Parameterized Constructor");
        }
        public override string ToString()
        {
            String str = "Society ID: " + societyID + " Resident Name: " + name + " Age: " + age;
            return str;
        }
    }
    class user
    {
        static string society_email;
        string login_time;
        static user()
        {
            society_email = "society@gmail.com";
        }
        public user()
        {
            login_time = DateTime.Now.ToString();
        }
    }
    class MyClass
    {
        static int a;
        static MyClass() { a = 10; }
        public MyClass() { }
    }
}

Output

Using Static Constructor in a Class
Using Static Constructor in a Class

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *