Flylib.com

Books Software

 
 
 

Recipe 3.14. Creating a Method That Accepts Different Sets of Arguments


Recipe 3.14. Creating a Method That Accepts Different Sets of Arguments

Problem

You have a great function that generates its results based on one type of data, but you'd like to reuse that function with other data types or argument signatures.

Solution

Use method overloading to provide different versions of the same method.

Discussion

You may sometimes write applications that communicate with Oracle databases. Supplying dates to Oracle SQL statements is frequently done using Oracle's TO_DATE function. When building SQL statements in my .NET application, you can prepare a Date variable for use in Oracle by first wrapping it in a TO_DATE function. There are other times when all you have is a date in a user -entered string format, and you need to prepare that date for use by Oracle. To support both original date and string data values, you can use an overloaded Oracle preparation function:

Public  
Overloads Function ToOracleDate( _
	      ByVal origDate As Date) As String
	   Return "TO_DATE('" & Format(origDate, "MM/dd/yyyy") & _
	      "', 'MM/DD/YYYY')"
	End Function

	Public Overloads Function ToOracleDate( _
	      ByVal origDate As String) As String
	   If (Trim(origDate) = "") Then
	      Return "NULL"
	   Else
	      Return ToOracleDate(CDate(origDate))
	   End If
	End Function

The Overloads keyword informs Visual Basic that you are trying to overload a single function name with two different argument signature variations. In this example, the string version calls the date version for some of its processing. This sharing of processing logic can help keep your code simple even when using multiple overloads.

The .NET Framework makes extensive use of method overloading, including over-loads of some Visual Basic features. The InStr () function, which locates a smaller string within a larger one, uses overloading to support the interesting syntax it inherited from Visual Basic 1.0. The basic syntax uses two strings, the one being searched and the one being sought:

Public Function InStr(ByVal String1 As String, _
	   ByVal String2 As String) As Integer

The second variation inserts an Integer starting position as the first argument:

Public Function InStr(ByVal Start As Integer, _
	   ByVal String1 As String, ByVal String2 As String) As Integer

Since Visual Basic does not support optional arguments anywhere but at the end of an argument list, this function uses overloading to support the argument variety.

Overloading is different from overriding . Overriding occurs only in inheritance relationships, when a function in a derived class alters or replaces the logic for an identical function in a base class. Overridden functions must have the same argument signature in both the base and derived classes.

There are no fixed limits on the number of overloads you can use in a single method. And while constructors ( Sub New procedures) also use a form of overloading, they do not require the Overloads keyword.

See Also

See Recipe 3.6 for information on overloading using class constructors.



Recipe 3.15. Using Standard Operators for Nonstandard Purposes

Problem

The basic Visual Basic operators, such as the addition operator (+), seem so useful that you would like to use them for your own custom classes.

Solution

Use operator overloading , a new feature in Visual Basic 2005, to allow your own classes to interact with each other through the standard Visual Basic operators.

Discussion

Operator overloading extends method overloading to include the standard Visual Basic operators. In a way, it treats operators such as +, *, and Or as method names . Consider a class that manages scientific specimens:

Class Specimen

If your application supports the idea of combining two specimens, resulting in a merged yet single larger specimen, it would be great to be able to use the addition operator to merge two distinct specimens into a single combined specimen:

Dim part1 As New Specimen
	Dim part2 As New Specimen
	Dim combinedParts As Specimen
	'…later…
	combinedParts = part1 + part2

To add support for addition to this class, overload the + operator by adding an Operator definition to the class:

Public Shared Operator +(ByVal firstPart As Specimen, _
	      ByVal secondPart As Specimen) As Specimen
	   Dim mergedSpecimen As New Specimen

	   ' ----- Add logic to merge the two parts, then…
	   Return mergedSpecimen
	End Operator

You can include different input or output types in the overloaded function, as long as at least one input or output matches the class in which the overload appears:

Public Shared Operator +(ByVal singlePage As Page, _
	      ByVal sourceBook As Book) As Book
	   ' ----- Adds a page to a book.

	End Operator

All overloaded operators must include the Shared keyword in the definition.

For unary operators, such as the Not operator, only a single argument is sent to the overloaded function. Table 3-1 lists the overloadable operators.

Table 3-1. Overloadable operators

Operator

Description

+(Unary)

Unary plus operator, as in the expression "+5." Unary plus is seldom used in standard Visual Basic programming, but you can use it for your own classes.

Shared Operator +(ByVal arg1 As Type) As Type

-(Unary)

Unary negation operator, as in "-5."

Shared Operator -(ByVal arg1 As Type) As Type

+

Addition operator , used to "add" items together.

Shared Operator +(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

-

Subtraction operator , used to "subtract" one item from another.

Shared Operator -(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

*

Multiplication operator.

Shared Operator *(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

/

Division operator.

Shared Operator /(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

\

Integer division operator.

Shared Operator \(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

Mod

Modulo operator.

Shared Operator Mod(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

&

Concatenation operator.

Shared Operator &(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

^

Exponentiation operator.

Shared Operator ^(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

<<

Shift left operator. Since the operand to the right of the standard operator is always an Integer , the second argument passed to the overload is also an Integer .

Shared Operator <<(ByVal arg1 As Type, _
	   ByVal arg2 As Integer) As Type

>>

Shift right operator. Since the operand to the right of the standard operator is always an Integer , the second argument passed to the overload is also an Integer .

Shared Operator >>(ByVal arg1 As Type, _
	   ByVal arg2 As Integer) As Type

=

Equal to comparison operator, for use in If and similar statements. You must also overload the related <> (not equal to) operator.

Shared Operator =(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Boolean

<

Less than comparison operator, for use in If and similar statements. You must also overload the related > (greater than) operator.

Shared Operator <(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Boolean

>

Greater than comparison operator, for use in If and similar statements. You must also overload the related < (less than) operator.

Shared Operator >(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Boolean

<=

Less than or equal to comparison operator, for use in If and similar statements. You must also overload the related >= (greater than or equal to) operator.

Shared Operator <=(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Boolean

>=

Greater than or equal to comparison operator, for use in If and similar statements. You must also overload the related <= (less than or equal to) operator.

Shared Operator >=(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Boolean

<>

Not equal to comparison operator, for use in If and similar statements. You must also overload the related = (equal to) operator.

Shared Operator <>(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Boolean

Not

Bitwise negation operator.

Shared Operator Not(ByVal arg1 As Type) As Type

IsTrue

Used to support overloading of the OrElse operator. You must also overload the related IsFalse operator, and you will probably want to overload Or as well.

Shared Operator IsTrue(ByVal arg1 As Type) _
	   As Boolean

IsFalse

Used to support overloading of the AndAlso operator. You must also overload the related IsTrue operator, and you will probably want to overload And as well.

Shared Operator IsFalse(ByVal arg1 As Type) _
	   As Boolean

And

Bitwise conjunction operator.

Shared Operator And(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

Or

Bitwise disjunction operator.

Shared Operator Or(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

Xor

Bitwise exclusion operator.

Shared Operator Xor(ByVal arg1 As Type, _
	   ByVal arg2 As Type) As Type

Like

Pattern comparison operator. The second operator is always a pattern string.

Shared Operator Like(ByVal arg1 As Type, _
	   ByVal arg2 As String) As Boolean

CType

Type conversion operator, for converting between different core and custom data types. Visual Basic supports two types of conversions: narrowing and widening . In narrowing conversions there is a chance that the source data will not fit in the target data type, as when converting a Long to an Integer . Conversions in the other direction are widening, and these never result in data loss. You must specify the type of conversion using the Narrowing or Widening keyword.

Shared [Narrowing  Widening] Operator _
	   CType(ByVal sourceData As Type) As Type


You can overload overloaded operators. That is, you can include multiple overloads for, say, the addition ( + ) operator in a single class, as long as the argument signatures differ .

While operator overloading can make your code more straightforward, it can also add a level of confusion, since you will be using operators in a way that is not part of the standard language usage. Where there is the possibility of confusion, add meaningful comments to the code to guide the reader through the rough spots.

See Also

Recipe 3.14 discusses standard method overloading.