C# Constructors

  • Whenever an instance of a class is created, a constructor of the class will be called.
  • Constructors can be used to set the initial values of the fields of the class.
  • An instance constructor is invoked whenever the class of the constructor is instantiated with new keyword.
  • A constructor looks like a special method which has the same name of the class without any return types.

The constructor without any parameters is called default constructor. If no constructor is not defined in a class, a default constructor will be generated automatically and the values of the class fields will be assigned to the default values of the data types.

Example 01-50-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;

namespace DefaultConstructor
{
    public class AAA
    {
        public int i;
    }

    class Program
    {
        static void Main(string[] args)
        {
            AAA a = new AAA();
            Console.WriteLine("The default value of i is {0}.", a.i);
            Console.Read();
        }
    }
}

Output

The default value of i is 0.

Explanation

  • Line 5-8: Define a public class AAA.
  • Line 7: Declare an integer field i.
  • Line 10: Start testing class Program. The access modifier is internal if it is not specified.
  • Line 12: The Main method starts.
  • Line 14: Create an instance of the class AAA and assigned it variable a. Because there is no constructor defined in class AAA, a default constructor is generated automatically and after running the constructor, the field i is set to its default value 0.
  • Line 15: Output the default value.

The most used constructors are instance constructors. For static constructor, we'll introduce it in static keyword section.

Example 01-50-02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;

namespace InstanceConstructor
{
    public class Athlete
    {
        public string name;
        public int distince;

        public Athlete()
        {
            name = "None";
            distince = 3000;
        }

        public Athlete(int mydist)
        {
            name = "None";
            distince = mydist;
        }

        public Athlete(string myname, int mydist)
        {
            name = myname;
            distince = mydist;
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Athlete a = new Athlete();
            Console.WriteLine("Name:{0}, Distince:{1}", a.name, a.distince);

            Athlete b = new Athlete(1500);
            Console.WriteLine("Name:{0}, Distince:{1}", b.name, b.distince);

            Athlete c = new Athlete("Mike", 5000);
            Console.WriteLine("Name:{0}, Distince:{1}", c.name, c.distince);
            
            Console.Read();
        }
    }
}

Output

Name:None, Distince:3000
Name:None, Distince:1500
Name:Mike, Distince:5000

Explanation

  • Line 5-28: Define a public class Athlete.
  • Line 7-8: Declare 2 fields name and distance.
  • Line 10-14: Define a default constructor. The name is the same as the class name and there is no parameter.
  • Line 12-13: Initialize values to the 2 fields.
  • Line 16-20: Define the second constructor with a parameter. The value of the parameter mydict will transfer to the field distance.
  • Line 22-26: Define the third constructor with 2 parameters. Parameter myname's value is assigned to the field name and mydict is assigned to the field distance.
  • Line 30-45: Testing class Program.
  • Line 32: Start Main method.
  • Line 34: Create an instance without arguments. So the default constructor will be called.
  • Line 35: Output the name and distance which were assigned in the default constructor.
  • Line 37: Create an instance without 1 argument. So the second constructor with one parameter will be called.
  • Line 35: Output the name and distance. 1500 is transferred as a argument.
  • Line 40: Create an instance without 2 arguments transferred. So the third constructor with 2 parameters will be called.
  • Line 41: Output the name and distance which are the exactly values we transferred.
  • Private constructors can prevent the class from being instantiated.
  • If no non-private constructor is defined and the default constructor is defined as private one, there is no way to create an instance of the class.
  • If no access modifier is specified, the constructor by default is set as a private constructors.

Example 01-50-03

The following example is changed from example 01-50-01.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;

namespace DefaultConstructor
{
    public class AAA
    {
        public int i;
        private AAA()
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            AAA a = new AAA();
            Console.WriteLine("The default value of i is {0}.", a.i);
            Console.Read();
        }
    }
}

Comparing with example 01-50-01, a private constructor in line 8-10 were added. When compiling the above example, you will get the following error message.

'PrivateConstructor.AAA.AAA()' is inaccessible due to its protection level

Because you are trying to instantiate the class AAA in line 17.