Implicit string conversion differences in C# and VB.NET: the case of strings and Boolean values

Posted: (EET/GMT+2)

 

Recently, I was delivering a C# training course for a group of people, and some of them had previous experience in Visual Basic and also a little in VB.NET. When the topic came to type conversions, we got into a discussion about implicit type conversions, in which C# and VB.NET take difference approaches. Let's see how a string-to-bool conversion works in these two languages.

In C#, the number of available implicit type conversions is limited. For instance, take a look at the following code:

// ** take 1: an IF statement
string input = null;
bool result;
if (input) // Error: Cannot implicitly convert 'string' to 'bool'.
{
    result = true;
}
else
{
    result = false;
}

// ** take 2: direct assignment
result = input; // Error: Cannot implicitly convert 'string' to 'bool'.

In both of these cases, the C# compiler gives an error message, which means you cannot get the above code to compile. However, in Visual Basic .NET, things are different. Take a look at the following code, similar to take 1 above:

Dim Input As String = "ABC"
If Input Then
    MessageBox.Show("True")
Else
    MessageBox.Show("False")
End If

This code compiles fine, and there is no syntactic error in the code above. However, if you would try to run the above code snipped, you'd get a runtime exception of type System.InvalidCastException.

Here's the interesting part: if the Input variable above would have the value of either "True" or "1" in Visual Basic, the above code would work just fine!