Turn string variable into boolean...

lidds

Junior Contributor
Joined
Nov 9, 2004
Messages
210
Is it possible to turn a string variable into a boolean variable

e.g:

Code:
dim simon as string = "true"
simon.toboolean()

Just an example.

Thanks in advance

Simon
 
I would just use a boolean from the begining, if that is beond your control I'd write a function like this.

Visual Basic:
'Untested Code but you get the idea.
Public Function IsTrue(sInput as String) as Boolean
        If lcase(sInput) = "true" Then
                Return True
        ElseIf lcase(sInput) = "false" Then
                Return False
        End If
End Function
 
Thanks a lot guys, someone else wrote the code and I've been asked to do a quick fix on it.

Simon
 
I beleive Convert.ToBoolean(simon) work too. Though I am unsure of the difference between that and Boolean.Parse().
 
Boolean.Parse specifically converts strings into Boolean values. Convert.ToBoolean converts anything into Boolean... so its flexible but Convert has to figure out that you are using a string. :)
 
Sorry, I guess I just like to split hairs. I wouldn't say that Convert really has to figure out that you are using a string. The compiler chooses the correct overload at compile time, so that essentially Convert.ToBoolean(String) is the same as Boolean.Parse(String).

There might be differences, for instance, localization, between the Parse methods and the Convert class. That, I'm not sure about.
 
The quick and simple solution (without needing to use or test any conversion methods) would be:

Visual Basic:
Dim simon As String = "true"
Dim b As Boolean

If simon = "true" Then
    b = True
Else
    b = False
End If
Simple may not always be the most sophisticated way of doing something, but it sure gets the job done :) (and did I mention language independent?)
 
I went digging into Reflector and found out a few things...

Boolean.Parse() will be slightly faster than Convert.ToBoolean because the current implementation of Convert.ToBoolean(String) calls Boolean.Parse().

Of note: Convert.ToBoolean(String) will return a "default" of false if you pass in null (Nothing in VB). A call to Boolean.Parse(null) will throw an exception.

If you know 100% that the string will always be "true" or "false" (and not "True" or "1" or "-1" or...), I'd find it Ok to go with the direct compare.

I actually had to write my own "IsBoolean(string)" function to handle some "odd" values, coming from a 3rd party. It had to interpret true/false, yes/no, 1/0, and a bunch of other values.

I didn't really have much to add, but I had already typed this all in... :)

-ner
 
Back
Top