Pallav Pallav - 3 months ago 10
Vb.net 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
Console.WriteLine("aaa")
End If
Console.ReadLine()


The same code in C#

string str = "aaa";
if(str.IndexOf("bbb") > -1)
{
Console.WriteLine("aaa");
}
Console.ReadLine();


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

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.

Comments