Hardik Nadiyana
Hardik Nadiyana

Reputation: 19

Error When Comparing A String To An Integer In VB.Net

In a simple program of VB.net, I am getting an output when I compare an integer with a string value. However, it should give me an error. Please let me know since this is a curious one.

The below program gives an output, let me know the reason why, since it should not:

Dim str as string
str = text1.Text.Length
if(str<5)
MsgBox("Below threshold")
end if

Upvotes: 0

Views: 2301

Answers (4)

Hardik Nadiyana
Hardik Nadiyana

Reputation: 19

As per your query, str is string variable and

Dim str as string
str = text1.Text.Length

will produce issue since 5 is integer value and str is string value so it has to generate error.

Upvotes: 0

David Wilson
David Wilson

Reputation: 4439

I thing that when you have a mixed type comparison, behind the scenes vb by default tries to convert the string to a double and then does the comparison. Really you should convert the string yourself to make the code easier to read and maybe easier to debug if something does happen.

To see these warnings in future,

Right click on the project name and then click properties at the bottom of the menu.

A window appears with all your project options. Click Compile.

Two thirds of the way down you have a list of warning configurations. Hopefully at the top of the list is Implicit Conversion. Change this from None to Warning and you'll see all these implicit conversions as warnings in your error list window. They wont stop the code running, but you can see them and deal with them if necessary.

Upvotes: 1

haraman
haraman

Reputation: 2742

Either declare str as Integer or convert str to Integer in comparison statement.

Dim str as Integer  

or

If (CInt(str) < 5) Then

Upvotes: 1

Mahadev
Mahadev

Reputation: 856

AS per your code, str is a string variable which you might want to compare with text1.text.

If you use

str = text1.text

that'll be the Variable Assignment, which will Assign a Value in text1 to str.

Then if you want to check what's in that variable, you should check like

if str="<value to check>"
    MessageBox.Show("<Message>") 'For you Information, MsgBox() is a deprecated method, Use MessageBox.Show() instead
end if

And now, what you are doing is, you are assigning length of the text entered in text1 to str which will Count the number of characters entered in text1 and assign that Integer value to str. So the above program is right if that's what you want to do and will not give error.

For any other doubt, feel free to ask.

Upvotes: 1

Related Questions