Constructors in C#
C#

Constructors in C#

Constructors in C# create the objects. Basically, the compiler provides a special function in a class called a constructor which it invokes automatically on the creation of an object. In this post, you will learn three types of constructors used in C# programming languagethe default constructor, parameterized constructor, and the copy constructor. However, there are two more types of constuctors available. These are the private constructor and the static constructor that we cover later.

Important Points Regarding Constructors in C#

  • The name of constructors is the same as that of the class in which it is defined.
  • You can not return a value from a constructor. So, there is no return type for the constructor.
  • Constructors can be declared as public. You can use an access modifier with constructors.
  • In a C# program, you can overload the constructors. Hence, you can define any number of constructors in a class.

The Default Constructor

The default constructor doesn’t take any parameter. If you don’t define any constructor then the compiler will itself provide the one. However, if you define any other constructor than the compiler will no longer provide the default constructor, and creating an object with a default constructor will result in a compile-time error. To illustrate this point, consider the following example

using System;
namespace ConsoleApp9
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass ob = new MyClass(); // Creating object with default constructor

        }
   }
    class MyClass
    {
        int a = 10, b = 10;
    }
}

Output:

No Error
No Error

However, as soon as we define a parameterized constructor, the program will not compile as illustrated below

using System;
namespace ConsoleApp9
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass ob = new MyClass(); // Creating object with default constructor

        }
   }
 
class MyClass
    {
        int a = 10, b = 10;
        public MyClass(int a, int b)
        {
            this.a = a;
            this.b = b;
        }
    }
}

The above code will not compile.

Parameterized Constructor

The parameterized constructor takes parameters as the input and assigns the value of parameters to the instance variable. In this case, the names of the constructor parameters may be the same as the names of the instance variable. In order to avoid this ambiguity, C# offers this keyword.

this Keyword

this keyword refers to the current object. You can access the instance variables of the current object using this keyword. For example, if the instance variable name and the constructor parameter name is the same, then you can access the instance variables using this keyword as shown in the following example:

public MyClass(int a, int b)
{
    this.a = a;
    this.b = b;
 }

Copy Constructor

When the constructor takes as an input parameter, the object of the same class in which it is defined, then it is a copy constructor. The copy constructor initializes the instance variables with the help of instance variables of the parameter object. Basically, the copy constructor creates another object containing the same values as an existing object.

Implementing Constructors in C#

The following program demonstrates the use of constructors in a class that defines the Complex numbers. As can be seen in the code, the class has two double type instance variables, rl, and img that represent the real and imaginary part of a complex number. There are three overloaded constructors defined in the class. In particular, the default constructor assigns the value 0.0 to both of the instance variables. However, the parameterized constructor and the copy constructor assign values as described earlier.

The class also has a ToString() function which returns a string comprising of the complex number in the given format as evident from the output. As a matter of fact, this method returns a string that the Console.WriteLine() method use to display the object value.

Furthermore, the Complex class has a method Add(), that returns another complex number by adding the two specified as parameters.

Finally, in the Main() method, we create three objects of the Complex class. Firstly, we create the two objects (ob1 and ob2) using the parameterized constructor. Secondly, we use a copy constructor to create the second object (ob2). Thirdly, we use the default constructor for creating the second object (ob2). In all cases, the third object (ob3) contains the sum of two objects ob1 and ob2 as shown in the output

using System;
namespace ConsoleApp9
{
    class Program
    {
        static voida Main(string[] args)
        {
            Complex ob1, ob2, ob3;
            ob1 = new Complex(3.5, 2.3);
            ob2 = new Complex(1.8, 7.3);
            ob3 = ob1.Add(ob1, ob2);
            Console.WriteLine("c1 = " + ob1);
            Console.WriteLine("c2 = " + ob2);
            Console.WriteLine("c3 = " + ob3);

            Console.WriteLine();

            ob2 = new Complex(ob1);
            ob3 = ob1.Add(ob1, ob2);
            Console.WriteLine("c1 = " + ob1);
            Console.WriteLine("c2 = " + ob2);
            Console.WriteLine("c3 = " + ob3);

            Console.WriteLine();

            ob2 = new Complex();
            ob3 = ob1.Add(ob1, ob2);
            Console.WriteLine("c1 = " + ob1);
            Console.WriteLine("c2 = " + ob2);
            Console.WriteLine("c3 = " + ob3);

            Console.WriteLine();
        }
   }
    class Complex
    {
        double rl, img;
        public Complex()
        {
            rl = img = 0;
        }
        public Complex(double rl, double img)
        {
            this.rl = rl;
            this.img = img;
        }
        public Complex(Complex c)
        {
            rl = c.rl;
            img = c.img;
        }
        public Complex Add(Complex c1, Complex c2)
        {
            Complex c3 = new Complex();
            c3.rl = c1.rl + c2.rl;
            c3.img = c1.img + c2.img;
            return c3;
        }
        public override string ToString()
        {
            String str = rl + " + " + img + "i";
            return str;
        }
    }
}

Output:

Constructors in C#
Constructors in C#

Related Topics

C# Examples

C# Arrays

Leave a Reply

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