If I try to put a string into a Boolean variable such as this:
Dim testValue As String = "True"
Dim bool1 As Boolean = testValue
With Option Strict On I get an error and the suggested fix is to change the second line to:
Dim bool1 As Boolean = CBool(testValue)
This is fine, But - what are the advantages / disadvantages of doing this instead:
Dim bool1 As Boolean = Boolean.Parse(testValue)
CBool feels very VB6 like to me but which should we be using and why?
If you know its a string in both cases, it should be an equivalent process. Since Cbool will eventually call a function to convert it. (As long as your value is "True" or "False")
There is a difference if you use something like cbool(value) and the value is a boolean.
from MSDN:
Note that the parse operation succeeds only if the string to be parsed is "True" (the value of the TrueString field) or "False" (the value of the FalseString field) in a case-insensitive comparison.
From MSDN in regards to Cbool (and other methods like that):
These functions are compiled inline, meaning the conversion code is part of the code that evaluates the expression. Sometimes there is no call to a procedure to accomplish the conversion, which improves performance. Each function coerces an expression to a specific data type
So, if you use cbool(value) if your value is a boolean it just uses it, no conversion required. That makes it potentially more efficient.
You can check this out too: Integer.Parse vs. CInt
I think the big difference is that Boolean.Parse is very strict about what it will accept (true/false) where as CBool is more lenient (0/1, true/false, I think yes/no although I'd have to retest that).
If you are ever going to port the code to C# or know that you will only ever have true/false values, then Parse would be the way to go. Otherwise, I would use CBool for its added flexibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With