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 ...
Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.