Pallav Pallav - 1 year ago 96 Question

Why does this If condition in VB.NET always evaluates to true and the same code in C# does not

I have same If condition in VB and C# as follows

Dim str As String = "aaa"
If (str.IndexOf("bbb")) Then
End If

The same code in C#

string str = "aaa";
if(str.IndexOf("bbb") > -1)

First of all you can not write if statement in C# with just IndexOf as condition you need to put > -1 to make it accept a boolean. But where as in VB you can write that,compiler does not give any error,and even if IndexOf returns -1 If always evaluates to true in VB. Why is this happening?

Answer Source

Because VB.NET provides an implicit conversion from the integer value to Boolean, it considers any non-zero integer expression to be true, similar to C/C++. C# won't let you do that. It insists that you provide a proper bool expression, hence the > operator.

If you were to use the same expression in VB.NET as you are using in C#, it would work the same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download