Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to VB.NET's Type Conversion functions (CBool) in C#?

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.

like image 960
Shimmy Weitzhandler Avatar asked Dec 09 '22 07:12

Shimmy Weitzhandler


2 Answers

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:

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.

The options it has available to do so include a direct cast (such as: (bool)var), an attempt to cast (using the as operator), calling one of the methods defined in the System.Convert class, calling the applicable Type.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 a bool. A direct cast won't work here.

like image 71
Cody Gray Avatar answered Mar 16 '23 07:03

Cody Gray


Take a look at the System.Convert class.

like image 27
Justin Niessner Avatar answered Mar 16 '23 06:03

Justin Niessner