Is there any alternative to VB's CBool
keyword in C#?
What about all the other functions?
CBool
will turn to a Boolean any valid boolean: 0
, "False"
, null
etc.
Is there any alternative to VB's CBool
keyword in C#?
What about all the other functions?
CBool
will turn to a Boolean any valid boolean: 0
, "False"
, null
etc.
The trick is that the
Cxx
"functions" in VB.NET aren't actually functions. In fact, they're more like operators that the compiler translates to what it determines is the "best-match" type conversion.Paul Vick used to have a great article about this on his blog, but all those pages seem to have been taken down now. MSDN (which is mostly accurate here) says:
The options it has available to do so include a direct cast (such as:
(bool)var
), an attempt to cast (using theas
operator), calling one of the methods defined in theSystem.Convert
class, calling the applicableType.Parse
method, and maybe some other strategies.There's no direct equivalent of this in C#: you have to do the compiler's thinking instead.
In this case, you'll almost certainly want to use the appropriate overload of the
Convert.ToBoolean
method because that particular method will have the necessary logic to convert the value into abool
. A direct cast won't work here.If you expect to be converting from one of the string values: "True", "true", "False", or "false", you should use Boolean.Parse. Instead of trying to be "smart" about it, Parse will "fail fast" if it doesn't get what it expects. By using a "smart" conversion when you don't really need it, you may mask errors at their source then have to track them down when they appear later in the code, which is usually more difficult.
Take a look at the
System.Convert
class.