SoFunction
Updated on 2025-03-06

Detailed explanation of C# constructor

1. Introduction

The basic usage of constructor is to complete the initialization work when the class object is declared.

2. Example constructor

1. The name of the constructor is the same as the class name.

2. When using new expression to create an object or structure of a class (such as int), its constructor will be called. And usually initializes the data members of the new object.

3. Unless the class is static, a default constructor will be automatically generated for classes without a constructor, and the object fields will be initialized using the default values.

4. The constructor can have parameters, and multiple constructors can exist in polymorphic form.

Code:

class CoOrds
    {
        public int x, y;
        // Instance constructor (default constructor)        public CoOrds()
        {
            x = 0;
            y = 0;
        }
        // Constructor with two parameters        public CoOrds(int x, int y)
        {
             = x;
             = y;
        }

        // Rewrite the toString method        public override string ToString()
        {
            return (("({0},{1})", x, y));
        }
        static void Main(string[] args)
        {
            CoOrds p1 = new CoOrds();//Calling the default parameterless constructor            CoOrds p2 = new CoOrds(5, 3);//Calling two parameter constructor
            // Use the override ToString method to display the results            ("CoOrds #1 at {0}", p1);
            ("CoOrds #2 at {0}", p2);
            ();
        }
    }

    /* Output:
     CoOrds #1 at (0,0)
     CoOrds #2 at (5,3)        
    */

analyze:

1. Where CoOrds() is a constructor, such constructors without parameters are called "default constructor".

(int x, int y) is also a constructor. The constructor can have parameters and allows polymorphism.

3. Static constructor

1. The static constructor does not use access modifiers or has no parameters.
2. The static constructor will be automatically called to initialize the class before creating the first instance or referring to any static member.
3. The static constructor cannot be called directly.
4. The user cannot control the time when the static constructor is executed in the program.
5. A typical usage of static constructors is when the class uses a log file and the constructor is used to write entries to this file.
6. Static constructors are also very useful for creating wrapper classes with unmanaged code. In this case, the constructor can call the LoadLibrary method.
7. If the static constructor raises an exception, the function will not be called again at runtime, and the type will remain uninitialized for the lifetime of the application domain where the program is running.

Code 1:

class TestClass
    {
        public static int x = 0;
        //Constructor        TestClass()
        {
            x = 1;
        }
        // Static constructor        static TestClass()
        {    //Step 2, execute x = 2            x = 2;
        }    
        //The first step is to execute the program entrance Main first.  Then execute public static int x = 0 and then execute the static constructor.        public static void Main(string[] args)
        {
            ("x:{0}", x); //Print, x = 2            TestClass Test = new TestClass();//The third step is to execute the constructor, at this time x = 1            ("x:{0}", x); //Print x = 1            ();
        }
    }

Analysis 1:

It is the program entrance. When executing Main, the first execution of public static int x = 0
2. Then execute the static constructor, at this time x = 2
3. Then execute the contents in the Main function and print x, at this time x = 2
4. Initialize TestClass, and then execute the constructor, at this time x = 1
5. Print x = 1

Code 2:

public class A
    {
        public static readonly int x;
        static A()
        {
            //The second step is called, here = 0, because the int type will be assigned a default value in the initialization stage, and the default value is 0.  Finally x = 0 + 1 (return to the first step)            x =  + 1;
        }
    }
    public class B
    {
        //The first step is to call, and then execute the static constructor of class A, waiting for the return (the second step returns = 1, so y = 1 + 1)        public static int y =  + 1;
        public static void Main(string[] args)
        {
            //The third step, = 1, y = 2.            ("x:{0},y:{1}。", , y);
            ();
        }
    }

Analysis 2:

1. First of all, each project has and can only have one static class Main function as an entry function. The entry function is first executed.
2. Since the Main function is in Class B, Class B will be initialized first. The initialization order of a class is: the static variables in the class, and then the static constructor is executed.
3. Start by running public static int y = + 1. When executing, y will be initialized to 0 and then the value of y will be calculated.
4. When calculating the value of y, the static variable x of A is called. So A will be initialized first.
5. When initializing A, first execute public static readonly int x, and first initialize x to 0.
6. Then execute the static constructor of A x = + 1 at this time y has been initialized to 0.
7. Calculate x = 1. Then go back to public static int y = + 1 to get y = 2.
8. Then execute the contents of the Main function. The result is x=1, y=2

4. Private constructor

A private constructor is a special instance constructor. It is usually used in classes that contain only static members. If a class has one or more private constructors without a public constructor, other classes (except nested classes) cannot create an instance of that class.

Code:

public class PrivateConstructor
    {
        private PrivateConstructor()
        {
            //PrivateTest a = new PrivateTest();
            // An error will be reported when opening the comment, error message: Not accessible because it is restricted by protection level.  Because the private constructor cannot be instantiated outside the class.        }
        public class PrivateTest
        {
            int i;
            private PrivateTest()
            {
                i = 3;
            }
            static void Main(string[] args)
            {
                PrivateConstructor t = new PrivateConstructor(); //Nested classes allow instantiation.                PrivateTest p = new PrivateTest(); //Instantiation is allowed within the class.                ("i:{0}", ); //Result: i:3                ();
            }
        }
    }

analyze:

Declaring an empty constructor prevents the automatic generation of default constructors. Note that if the access modifier is not used for the constructor, it is still a private constructor by default. However, it is often explicitly used to explicitly indicate that the class cannot be instantiated.

This is all about this article about C# constructors. I hope it will be helpful to everyone's learning and I hope everyone will support me more.