O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Create a Convertible Object

Problem

You want to create a class that can be converted to common data types such as Int32 and String.

Solution

Implement the IConvertible interface. Add conversion code for the supported data types, and throw an InvalidCastException for all unsupported data types.

Discussion

The IConvertible interface defines 17 methods for converting an object into basic .NET types. The first method, GetTypeCode, simply returns a value from the System.TypeCode enumeration identifying the type, which will always be TypeCode.Object for your custom classes, as shown here:

Public Function GetTypeCode() As TypeCode _
  Implements IConvertible.GetTypeCode
    Return TypeCode.Object
End Function

The other 16 methods perform the actual conversions and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required