Visual Basic.NET Language Enhancements: Overloading

Category:
C#, VB.NET, ASP.NET
Type:
Snippets
Difficulty:
Beginning

Author: Intelligent Solutions Inc.

Version Compatibility: Visual Basic.NET

More information:
This is Part 3 of 5 mini-articles that were originally published in the FreeVBCode.com newsletter language enhancements in Visual Basic.NET.

Instructions: Copy the declarations and code below and paste directly into your VB project.

Overloading

Overloading refers to the use of subroutines or functions with the same name but different signatures (i.e., different parameter lists).

In languages that support overloading (such as C++ and Java) you can have code such as the following:

Function GetUserId(UserName as String) as Long

End Function

Function GetUserId(OrderID as Long) as Long

End Function

At runtime, the version of GetUserId invoked is determined by the variable type passed to it. In VB6, code such as this will not compile.

Overloading permits more elegance and less error checking in your applications. From a functional perspective, you can implement overloading in VB6 by using the variant data type. For an example, look at http://www.freevbcode.com/ShowCode.Asp?ID=40, which returns true if all values in a list (either an array or a collection) are unique, and false otherwise.

The function signature of this example is:

Public Function ContainsUniqueValues(vList As Variant) As _
Boolean

To do its work, the function has to:

  • ensure that vList is either an array or a collection by using VB's VarType and TypeOf methods.
  • Raise an error if vList is not an array or a collection.
  • include messy "If - elseif" type logic to accomplish the two tasks above.

In VB.NET, overloading could perform the same task via functions with the following signatures (note: the below is only one possible alternative; several other solutions are available):

Public Function ContainsUniqueValues(colList As Collection) As _
Boolean

Public Function ContainsUniqueValues(asList() As String) As _
Boolean

Public Function ContainsUniqueValues(alList() as Long) As _
Boolean

This will allow for passing a collection, an array of strings, or an array of longs to the function of the same name. It will reduce the amount of code within the functions themselves and increase readability on both the calling and the callee side.

The rest of the series:

Part I, Inheritance
Part II, Polymorphism
Part IV, Constructors
Part V, Free-Threading