ToDouble method. However, since you removed the constraint, the possibility
of getting a runtime exception exists, for example, when the type represented by T doesn??™t
implement IConvertible. Since generics are meant to provide better type safety and help you
avoid runtime exceptions, there must be a better way. There is, and you can do better by giving
Complex(Of T) yet another converter in the formof a Convert(Of T, Double) delegate in the
constructor, as follows:
Imports System
Imports System.Collections.Generic
Public Structure Complex(Of T As Structure)
Implements IComparable(Of Complex(Of T))
'Delegate for doing multiplication.
Public Delegate Function BinaryOp(ByVal val1 As T, ByVal val2 As T) As T
Private mReal As T
Private mImaginary As T
Private mult As BinaryOp
Private add As BinaryOp
Private convToT As Converter(Of Double, T)
Private convToDouble As Converter(Of T, Double)
CHAPTER 12 n GENERICS 266
Public Sub New(ByVal real As T, ByVal imaginary As T, ByVal mult As BinaryOp, _
ByVal add As BinaryOp, ByVal convToT As Converter(Of Double, T), _
ByVal convToDouble As Converter(Of T, Double))
Me.mReal = real
Me.mImaginary = imaginary
Me.mult = mult
Me.add = add
Me.convToT = convToT
Me.convToDouble = convToDouble
End Sub
Public Property Real() As T
Get
Return mReal
End Get
Set(ByVal value As T)
mReal = value
End Set
End Property
Public Property Img() As T
Get
Return mImaginary
End Get
Set(ByVal value As T)
mImaginary = value
End Set
End Property
Public ReadOnly Property Magnitude() As T
Get
Dim mMagnitude As Double = _
Math.
Pages:
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431