Because constructors are effectively methods, they support the overloading feature. You can therefore provide multiple implementations of the New
method, taking care of the limitations described for methods. You cannot use the Overloads
keyword; the compiler does not need it. For example, continuing the example of the Contact
class, we can provide different implementations of the constructor as follows:
The first overload receives no arguments and provides a default members’ initialization. The second overload receives just an argument, initializing other members with empty strings. The last overload is the most complete and provides initialization features for all the properties exposed by the class.
Overloads are useful, but when working with constructors, you might want to consider a common place for initializing members. To accomplish this you can invoke constructors’ overloads from another overload. For example, consider the following code snippet:
The first overload can invoke the second overload, passing required arguments. In the preceding example only an empty string is passed, but according to your scenario you could make a different elaboration before passing the argument. The good news in this technique is that you need to provide initialization code only once (in this case, in the second overload). By the way, take care about the hierarchical calls; the first overload can invoke the second one because this receives more arguments but not vice versa. This kind of approach can be used also because both overloads have an argument in common; for example, if you instead also had a ContactID
property of type Integer
that you wanted to initialize via the constructor and you had the following overloads:
In this case the two overloads have no arguments in common; because of this, if you want to provide a common place for initializations, you need to implement a private constructor as follows:
Then you can redirect both preceding overloads to invoke a private constructor:
There is a little bit more to say about private constructors that is discussed later in this chapter about shared members. At the moment you need to remember that if you place a private constructor, you must remove the public one with the same signature. For example, if you have a Private Sub New()
, you cannot also have a Public Sub New()
.
18.222.3.255