iformatprovider for boolean

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello

There doesn't appear to be an iformatprovider for to specify the format to convert a boolean to.

i.e. MyBool.ToString("YES/NO") does not work

Any workarounds?
 
Eric,
Create a class that implements IFormatProvider, such that it returns an
object that implements ICustomFormatter. Within the ICustomFormatter.Format
method return the string that you desire...

Something like:

Namespace Gofoth

Public Class Eric

Public Shared Sub Main()

Dim s As String

' the format string is "true value; false value"

s = String.Format(New BooleanFormatter, "{0:Yes;No}", False)
s = String.Format(New BooleanFormatter, "{0:Yes;No}", True)
s = String.Format(New BooleanFormatter, "{0:On;Off}", False)
s = String.Format(New BooleanFormatter, "{0:On;Off}", True)


End Sub

End Class

Public Class BooleanFormatter
Implements ICustomFormatter
Implements IFormatProvider

#Region " Custom formatter support "

Public Function Format(ByVal formatString As String, ByVal arg As
Object, ByVal formatProvider As System.IFormatProvider) As String Implements
System.ICustomFormatter.Format

If formatString Is Nothing OrElse Not TypeOf arg Is Boolean Then

If TypeOf arg Is IFormattable Then
Return DirectCast(arg,
IFormattable).ToString(formatString, formatProvider)
Else
Return arg.ToString()
End If
End If
Dim sections() As String = formatString.Split(";"c)
Dim argBool As Boolean = DirectCast(arg, Boolean)
If argBool Then
Return sections(0)
Else
Return sections(1)
End If
End Function

#End Region

#Region " Format provider support "

Public Function GetFormat(ByVal formatType As System.Type) As Object
Implements System.IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function

#End Region

End Class

End Namespace

Note you can use the BooleanFormatter from String.Format and other methods
that accept a format specifier & a format string, however you cannot use it
from Boolean.ToString, as Boolean to not support IFormattable.

Hope this helps
Jay
 
Back
Top