By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,911 Members | 1,186 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,911 IT Pros & Developers. It's quick & easy.

iformatprovider for boolean

P: n/a
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?
Nov 20 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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

"Eric Gofoth" <an*******@discussions.microsoft.com> wrote in message
news:55**********************************@microsof t.com...
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?

Nov 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.