What is a constructor?

Answer:
A constructor is a special type of function that gets called every time you initialize a class.

For example, say you have this class called Person:
class Person
{
public Person ()
{
Console.WriteLine("We're making a new person");
}
}

Now you can create a new object of type Person, like this:
Person Bob= new person();

The program will write the line "We're making a new person" to the screen.


That seems useless right now, but say you want to do a specific task when you create a new person. Maybe you want to create a new folder when a new person is made. The class may look more like this:
class Person
{
public Person ()
{
Directory.CreateDirectory("C:/people/newperson");
}
}

Now that's great, but this folder has nothing to do with the specific person I have created. The more useful feature of a constructor is that it takes arguments just like a normal method does. So now I can pass it the persons name so we can make the right folder name. Here's the code:
class Person
{
public Person (string personName)
{
Directory.CreateDirectory("C:/people/"+personName);
}
}

Now here's how to use it.
Person Bob= new Person("bob");

This will create a Person class called Bob that I can use in my code as well as a folder named bob on my c drive.

Constructor, as the name suggests is a special function in the program which is invoked before the object is created
A constructor doesn't allow any arithmetic functions i.e its not allowed to peform addition, subtraction or any type of function inside a constructor except declaration of variables.
So a constructor is used to declare variables before the object of the class/program is created.


Hope your question is resolved.
Cheers,
Aaditya A. Damani
First answer by ID3705787059. Last edit by Wannaanswer. Contributor trust: 3 [recommend contributor recommended]. Question popularity: 34 [recommend question].