C#

Private and Static Constructors in C#

Programmingempire

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

Further Reading

Selection Sort in C#

Insertion Sort in C#

Bubble Sort in C#

How to Create Instance Variables and Class Variables in Python

Comparing Rows of Two Tables with ADO.NET

Example of Label and Textbox Control in ASP.NET

One Dimensional and Two Dimensuonal Indexers in C#

Private and Static Constructors in C#

Methods of Array Class

Anonymous Functions in C#

Programs to Find Armstrong Numbers in C#

Matrix Multiplication in C#

One Dimensional and Two Dimensional Indexers in C#

Static Class Example in C#

Rotating an Array in C#

Generic IList Interface and its Implementation in C#

Recursive Binary search in C#

C# Practice Questions

Creating Navigation Window Application Using WPF in C#

Find Intersection Using Arrays

An array of Objects and Object Initializer

Performing Set Operations in LINQ

Using Quantifiers in LINQ

Data Binding Using BulletedList Control

Grouping Queries in LINQ

Generic Binary Search in C#

Understanding the Quantifiers in LINQ

Join Operation using LINQ

Deferred Query Execution and Immediate Query Execution in LINQ

Examples of Query Operations using LINQ in C#

An array of Objects and Object Initializer

Language-Integrated Query (LINQ) in C#

How Data Binding Works in WPF

Examples of Connected and Disconnected Approach in ADO.NET

New Features in C# 9

IEnumerable and IEnumerator Interfaces

KeyValuePair and its Applications

C# Root Class – Object

Access Modifiers in C#

Learning Properties in C#

Learning All Class Members in C#

Examples of Extension Methods in C#

How to Setup a Connection with SQL Server Database in Visual Studio

Understanding the Concept of Nested Classes in C#

LINQ To SQL Examples

A Beginner’s Tutorial on WPF in C#

Explaining C# Records with Examples

Everything about Tuples in C# and When to Use?

Creating Jagged Arrays in C#

Linear Search and Binary search in C#

Learning Indexers in C#

Object Initializers in C#

Examples of Static Constructors in C#

When should We Use Private Constructors?

C# Basic Examples

IEqualityComparer Interface

programmingempire

You may also like...