Constructors
Constructors are the "setup" methods of your classes. They are fired whenever your class is instantiated. You are not required to write code for a constructor, but if you do not, the base class constructor will fire anyway. At the very least, the base class is System.Object, so the constructor for this class will fire.
Notice the syntax of a constructor. In C#, it's simply the name of the class. In VB.NET, it's a special Sub called New. This is true for every class, and it's what differentiates it from other methods in the class. |
Listing 2.2. Instantiating an object
C#
VB.NET
Car myCar = new Car();
The car's constructor method, if there is one, is fired as soon as we create this new car object called myCar. In our class, the code is simply a method with the same name as the class in C#, or the New keyword in VB:
Dim myCar As New Car()
Listing 2.3. A basic constructor
C#
VB.NET
public Car()
{
// code
}
Through overloading (we'll talk about that shortly), you can even pass in parameters to your constructor. This gets back to the notion of setting some initial values for your class when it's instantiated. Say we wanted to make our car a certain color when we created it. We might write a constructor like this:
Public Sub New()
' code
End Sub
Listing 2.4. A constructor with a parameter
C#
VB.NET
public Car(string newColor)
{
Color = newColor;
}
Assuming for a moment that there is a property called Color, we take the parameter in the constructor, NewColor, and assign it to the Color property. Creating a Car object with a color, then, would look like this:
Public Sub New(newColor As String)
Color = newColor
End Sub
Listing 2.5. Instantiating an object with a parameter
C#
VB.NET
Car myCar = new Car("Red");
Dim myCar As New Car("Red")