Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a string value used as a boolean

I was playing around with my code in VB.NET (Visual Studio IDE) when I realised that I could affect a boolean value into a string

The string consequently took the value "True" or "False"

I then tried using it as a boolean such as

If StringValueContainingTrueOrFalse then
    'Do Something
End if

This also worked and is giving the desired result. This made me realise how little I knew about how things worked in the background.

Is the word True in the string being detected and the IDE is smart enough to deal with it or does it simply try to convert the value to what it needs to be (so knowing that it needs a boolean value try to convert the string into one to do it's actions) ?

What is happening making this possible ?

like image 260
micbobo Avatar asked Feb 11 '23 08:02

micbobo


1 Answers

It's not the IDE doing it, rather it's doing a runtime cast from one type to another. If the string contains a value that can be cast to a boolean, you're fine. If not, you'll get a runtime error.

I would recommend using Option Strict On to get compile time errors instead, so you don't unintentionally rely on runtime casting you're not aware of. If you turn this option on, the code in your question won't compile.

like image 76
James Thorpe Avatar answered Feb 13 '23 03:02

James Thorpe