Home / Questions / What are constructors in C#?
Explanatory Question

What are constructors in C#?

👁 809 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

A constructor is a member function in the class and has the same name as its class. Whenever the object class is created, the constructor is automatically invoked. It constructs the value of data members while initializing the class.

Default Constructor in C#

A constructor without any parameters is called a default constructor; in other words, this type of constructor does not take parameters. The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class with different values. The default constructor initializes: 

  1. All numeric fields in the class to zero.
  2. All string and object fields to null.
using System;
namespace DefaultConstractor
{
    class addition
    {
        int a, b;
        public addition()   //default contructor
        {
            a = 100;
            b = 175;
        }

        public static void Main()
        {
            addition obj = new addition(); //an object is created , constructor is called
            Console.WriteLine(obj.a);
            Console.WriteLine(obj.b);
            Console.Read();
        }
    }
}

Now run the application, the output will be as following:

100
175

Parameterized Constructor in C#

A constructor with at least one parameter is called a parameterized constructor. The advantage of a parameterized constructor is that you can initialize each instance of the class with a different value.

using System;
namespace Constructor
{
    class paraconstrctor
    {
      public  int a, b;
      public paraconstrctor(int x, int y)  // decalaring Paremetrized Constructor with ing x,y parameter
        {
            a = x;
            b = y;
        }
   }
    class MainClass
    {
        static void Main()
        {
            paraconstrctor v = new paraconstrctor(100, 175);   // Creating object of Parameterized Constructor and ing values
            Console.WriteLine("-----------parameterized constructor example by vithal wadje---------------");
            Console.WriteLine("\t");
            Console.WriteLine("value of a=" + v.a );
            Console.WriteLine("value of b=" + v.b);
            Console.Read();
        }
    }
}
value of a=100
value of a=175