In this article, we will learn about the Private constructor in C# with multiple examples. First of all, Constructor in C# is the special method of the class which is used to initialize the data members of the new object. Every class in C# must have a constructor which gets automatically invoked when the new object of the class is created.
C# Private Constructor
Private constructor: In C#, A parameterless constructor with a private access modifier in a class is known as a private constructor. It is a special instance constructor which is mainly used to control the instantiation of a class.
A Private constructor is generally used with the class having static data members only.
The main intention behind the private constructor is to control the object creation and to stop explicit inheritance.
In C#, The Copy constructor is a constructor that creates an object by cloning data from one object to another. It can be used to copy data from an existing object to a new object without changing the value of the existing object. The copy constructor is a parameterized constructor that accepts objects of the same type as parameters.
C# does not provide a copy constructor for the objects, but we can write one by ourselves based on our needs.
A class can have multiple constructors in order to create a copy constructor.
Now in this post, We will learn about the static constructor with examples in C#.
C# Static Constructor
A static constructor is a special kind of constructor that invokes automatically before the first instance of a class is created. It is used to initialize only static data members of the class or to write the code that needs to be executed only once throughout the execution of the program.
The purpose of using a static constructor is to trigger a piece of code automatically without creating an object of a class.
Static Constructor Syntax
In the below sample program, a static constructor is created without any parameter and access modifier.
In C#, Constructors are special types of methods that get executed when an instance of the classor structis created.
The main use of the constructor is to initialize and set the default values for the data members of the new object. It looks very similar to a method, but with no return type and have the same name as the class or struct.
A constructor is invoked when we use the new operator or the reflection (Example: Activator. CreateInstance) to create an object of a class.
If we forget to define the default constructor in a class, the compiler will automatically create one system-defined default constructor for that class.
The default constructor is used to initialize all the numeric fields/variables in a class to zero and all the string fields and object to null.
C# Constructor Syntax
Following is the syntax to create a constructor in C#
In the above example, we have created constructor “User” with the same name as class or struct.