.NET Tips and Tricks

Blog archive

Defining Conversions for Visual Basic Classes

Sometimes you have to repeatedly convert one of your custom classes into something else. In Visual Basic, your conversions come in two types: Widening conversions and narrowing conversions. In a widening conversion, the new object holds all of the data of the original object: no errors can occur in this conversion and no data will ever be lost. In a narrowing conversion, the new object holds only some of the original object's data: some data may be lost and errors may occur.

As an example, consider three objects: a TypicalCustomer that holds the data that 80 percent of your customers require, a PremiumCustomer adds some more data to support additional functionality, and a DeadbeatCustomer (which has the least amount of functionality) that holds less data. Converting a TypicalCustomer to PremiumCustomer would be a widening operation, while converting a TypicalCustomer to a DeadbeatCustomer would be a narrowing conversion.

To add the code to convert a TypicalCustomer object to either a PremiumCustomer or a DeadbeatCustomer object, you add an Operator member (not a Function or Sub) to the class for each conversion. The member must be called CType, accept the object that you're converting from, and return the object you're converting to. The member must also be declared as Public Shared, and flagged as either Widening or Narrowing. The code to add to a TypicalCustomer class to support converting it to a PremiumCustomer or a DeadbeatCustomer would look like this:

Public Class TypicalCustomer
  Public Shared Widening Operator CType(ByVal Customer As TypicalCustomer) As PremiumCustomer
    Dim pc As New PremiumCustomer
    'transfer data from the Customer parameter to pc
    Return pc
  End Operator
  Public Shared Narrowing Operator CType(ByVal Customer As TypicalCustomer) As DeadbeatCustomer
    Dim dbc As New DeadbeatCustomer
    'transfer some of the data from the Customer parameter to dbc
    Return dbc
  End Operator
End Class

Your CType method is automatically invoked when the appropriate conversion is required. If your code has Option Strict Off, the difference between a widening and narrowing conversions doesn't matter, as in this example:

Dim tc As New TypicalCustomer
Dim pc As PremiumCustomer
Dim dbc As DeadbeatCustomer

pc = tc
dbc = tc

But if you're using Option Strict On, narrowing conversions can only be performed using Visual Basic's CType function, as in this example:

dbc = CType(cm, DeadbeatCustomer)

Posted by Peter Vogel on 03/13/2014


comments powered by Disqus

Featured

Subscribe on YouTube