ToString() directly.
Examples of String Formatting in Custom Types
Let??™s take a look at another example using the venerable Complex type that we??™ve used before.
This time, let??™s implement IFormattable on it to make it a little more useful when generating a
string version of the instance:
CHAPTER 9 n WORKING WITH STRINGS 175
Imports System
Imports System.Text
Imports System.Globalization
Public Structure Complex
Implements IFormattable
Private real As Double
Private imaginary As Double
Public Sub New(ByVal real As Double, ByVal imaginary As Double)
Me.real = real
Me.imaginary = imaginary
End Sub
'IFormattable implementation
Public Overloads Function ToString(ByVal format As String, _
ByVal formatProvider As IFormatProvider) As String _
Implements IFormattable.ToString
Dim sb As StringBuilder = New StringBuilder()
If format = "DBG" Then
sb.Append(Me.[GetType]().ToString() & "" & vbCrLf & "")
sb.AppendFormat("" & vbTab & "real:" & vbTab & _
"{0}" & vbCrLf & "", real)
sb.AppendFormat("" & vbTab & "imaginary:" & vbTab & _
"{0}" & vbCrLf & "", imaginary)
Else
sb.Append("( ")
sb.Append(real.ToString(format, formatProvider))
sb.Append(" : ")
sb.Append(imaginary.ToString(format, formatProvider))
sb.Append(" )")
End If
Return sb.
Pages:
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298