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.
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:
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
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
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.