Constructors





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.


One of the most typical uses for a constructor is to set initial values for different properties in the class. If you have a Name property, for example, its value will be null when the class is instantiated, unless you specify some value for it (maybe an empty string) in the constructor.

You don't call a constructor directly. It's fired when you instantiate the object. Recall the creation of our car:

Instantiating an object

C#

Car myCar = new Car();


VB.NET

Dim myCar As 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:

A basic constructor

C#

public Car()
{
  // code
}


VB.NET

Public Sub New()
  ' code
End Sub

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:

A constructor with a parameter

C#

public Car(string newColor)
{
  Color = newColor;
}


VB.NET

Public Sub New(newColor As String)
  Color = newColor
End Sub

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:

Instantiating an object with a parameter

C#

Car myCar = new Car("Red");


VB.NET

Dim myCar As New Car("Red")


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows