Constructors

A constructor is a special type of method that is automatically called when the object is instantiated or created. Its purpose is to initalize the object's state. The constructor has to be the same name as the class name. For our Car class, it would have to be named Car. The basic constructor for our car class from the last page would be this:

public Car(string owner, string make, string model, string color, string vin, string regNumber) {
    Owner = owner;
    Make = make;
    Model = model;
    Color = color;
    VIN = vin;
    RegNumber = regNumber;
}

Overloading Constructors

Now sometimes, we want to give the user to option to insert certain parameters but not other parameters. This is where overloading comes into play. Overloading constructors allows us to have multiple constructors. For example, in this case if we want the user to able to "make" a car without having a VIN number, we can make another constructor below our first one like this:

public Car(string owner, string make, string model, string color) {
    Owner = owner;
    Make = make;
    Model = model;
    Color = color;
}

You may be asking, "How does C# know what constructor to use?"

If you look at the first constructor, the parameter list contains 6 strings. The second constructor contains 4 strings. The name of the parameter does not matter. The only things that matter is the data type(string, int, double) and the order.

If you try and make a new constructor with 6 strings, C# will give you an error saying that this is not possible.ERROR

As the image shows, the error says "parameter types" not parameter names.

Now that we can actually create Cars using our constructor, lets do that in our Program.cs.

Car car = new Car("John Doe", "Honda", "Civic", "White");

Congratulations, you just made your first object. We call this an instance of the car class. But....we cannot do anything with that object. Let's do that in the next section.

Created our first Account

Now that we have made all the variables asociated with an account, let's make the constructor

public Account(string name, int age, double balance) {
    Name = name;
    Age = age;
    Balance = balance;
}

Now that we have made the constructor, we can actually initalize an object in our Main.cs.

Account account = new Account("John Doe", 13, 500.00);

With this new class, we can now make accounts on the fly without having to intialize multiple variables like we were doing before. In the next section, we will refactor(redo to make better) the Main.cs class so that it uses the Account class instead of the three variables we made before.

Next Section: Methods/Functions