![]() | ![]() |
A constructor is a method that executes automatically whenever an object of a class is created. In fact, when you create an object of a class, you use the new keyword followed by the name of the constructor. For instance, when we created “plane1” object using the syntax “new AirPlane()”, here “AirPlane()”is basically a constructor which is created by default when we created the “AirPlane” class.
A constructor is normally used to initialize class variables. We can override default constructor and provide our own implantation of the constructor. Take a look at the following script:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyProgram
{
class Program
{
static void Main(string[] args)
{
// Creating Object of the Airplane Class
AirPlane plane1 = new AirPlane();
// Accessing class members from plane1 object
Console.WriteLine(plane1.planeMake);
Console.WriteLine(plane1.planeModel);
// Accessing class methods from plane1 object
plane1.StartPlane();
plane1.StopPlane();
Console.ReadKey();
}
}
class AirPlane
{
public string planeMake;
public string planeModel;
public AirPlane()
{
planeMake = "Airbus";
planeModel = "A350";
}
public void StartPlane()
{
Console.WriteLine("Plane Started");
}
public void StopPlane()
{
Console.WriteLine("Plane Stopped");
}
}
}
In the script above, we created a constructor in the “AirPlane” class. Inside the constructor, we assigned some values to the “planeMake” and “planeModel” variables. You can see that the name of the constructor is the same as the name of the class. However, a constructor has no return type, not even void return type. A constructor should always be public since most of the time an object of a class is being created inside another class. The output of the script above looks like this: