Recall that classes are an abstract definition, listing functionality that is provided. In addition to properties, methods, and events, classes contain constructors. A constructor is a special method that is used to create an instance of the class.
Constructors always have the same name as the class. For example, one of the classes used to programmatically work with database data is the SqlCommand class. The constructor for this class is a method named SqlCommand(). To create an instance of an object, we use the following syntax: Variable = New Constructor() The constructor Constructor returns an object of the class Constructor. Because Visual Basic is a strongly typed language, the type of Variable must be of the class whose constructor is being called. For example, to create an instance of the SqlCommand class, we would first create a variable whose type was of SqlCommand as follows: Dim myCommand as SqlCommand And then we would assign to this variable the object returned by the constructor: myCommand = New SqlCommand() The first line of code creates a variable named myCommand of type SqlCommand; the second line of code assigns to myCommand the object returned by the constructor SqlCommand().
Constructors with ParametersConstructors, like functions and subroutines, can have zero or more parameters. Additionally, classes may have more than one constructor. When constructors accept one or more parameters, typically the parameters are for initial values of various properties. For example, the SqlCommand class has a constructor that accepts zero parameters, as well as one that accepts a string parameter. The constructor that accepts zero parameters does not assign any initial value to any of its properties. The constructor that accepts a string parameter, however, assigns the passed-in parameter value to the object's CommandText property.
Constructors that accept more than one parameter are used frequently for reducing the amount of code that needs to be written. For example, to create an SqlCommand object and set its CommandText property, we would need to use the following two lines of code: Dim myCommand as SqlCommand = New SqlCommand() myCommand.CommandText = "some value" However, by using the SqlCommand() constructor that accepts a string parameter, we can condense these two lines into one as follows: Dim myCommand as SqlCommand = New SqlCommand("some value")
|