I was experimenting with message boxes, and tried a simple yes/no messagebox So I wrote this simple piece of code. However, the "chc" variable always returns as 1, no matter what button I press. I provided the code, so you maybe see what I did wrong. It is probably horribly wrong.
If MsgBoxResult.Yes Then
chc = 1
ElseIf MsgBoxResult.No Then
chc = 0
End If
MsgBox(chc)
The
MsgBox()
method is returningMsgboxResult
Enumeration, check the value that the method returns:Turn on strict compilation.
Option Strict On
at the top of your file.Really, do it. It is one if the easiest, quickest ways to catch all sorts of errors before they happen. You might get hours of your life back. I'm not exaggerating.
With strict compilation turned off, the compiler sees this:
And says, 'If/then checks for whether a condition is true or false.
MsgBoxResult.Yes
isn't a boolean - it's an integer. But I'll convert it, and say that anything other than zero is true.'The problem is that all values for
MsgBoxResult
are non-zero. So evenMsgBoxResult.No
is "true."With
Option Strict On
, you'll get this compiler error:And as soon as you see it, you'll realize that you meant
and you'll fix it before you even run the program.
Compiler errors are better than runtime errors because you don't have to debug the code to figure out what's wrong, or worse, have a user report it and then have to figure out what went wrong. We all make little errors, and the compiler catches them right away.
When you turn on strict compiling, you might see tons of other errors. Each and every one of those is something that could possibly cause a runtime error.
Having strict compiling turned off allows us to do all sorts of evil things like
Then if you call
You get a runtime error,
It's like having a two-direction highway instead of letting cars drive all over the place and hoping they don't hit each other. It's not guaranteed to prevent accidents, but it eliminates a huge potential cause.