How string value is used as boolean

I played with my code in VB.NET (Visual Studio IDE) when I realized that I could affect a boolean value in a string

The string, therefore, takes the value "True" or "False"

Then I tried to use it as a logical one, for example

If StringValueContainingTrueOrFalse then 'Do Something End if

It also worked and gives the desired result. It made me realize how little I knew about how everything worked in the background.

Is the word True in the detected string, and the IDE is smart enough to handle it, or just trying to convert the value to what it needs (so, knowing that it needs a logical value, try converting the string to one to perform actions )?

What happens by making this possible?

+4
source share
4 answers

If a non-Boolean expression is used in the IF expression, the Vb.Net compiler converts the expression to Boolean using the method Conversions.ToBoolean.

Your code is equal

If Conversions.ToBoolean(StringValueContainingTrueOrFalse) then
    'Do Something
End if

If your value can be converted to logical, everything will be fine. Otherwise, an exception will be thrown.

For instance:

Sub Main
    Dim StringValueContainingTrueOrFalse as String = "True"

    IF StringValueContainingTrueOrFalse then
    Console.WriteLine("true")
    end if  
End Sub

The above program generates the following IL:

IL_0000:  ldstr       "True"
IL_0005:  stloc.0     // StringValueContainingTrueOrFalse
IL_0006:  ldloc.0     // StringValueContainingTrueOrFalse
IL_0007:  call        Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean
IL_000C:  brfalse.s   IL_0018
IL_000E:  ldstr       "true"
IL_0013:  call        System.Console.WriteLine
IL_0018:  ret

You can see that the method call is shown on the label IL_0007 Conversions.ToBoolean.

+2
source

IDE , . , , . , .

Option Strict On , , . , .

+3

VB Boolean If, Boolean, .

/ .

.

Option Strict On

. MSDN VB.Net If:

https://msdn.microsoft.com/en-us/library/752y8abs.aspx

. Expression. True False , Boolean.

+2
source

When String is directly used in status if, it will try to convert it to Boolean so that it can perform the evaluation. True or False can be converted to Booleans, but other values ​​cannot.

Module Module1
    Sub Main()
            Dim StringValueContainingTrueOrFalse As String = "True"
        If StringValueContainingTrueOrFalse Then
            Console.WriteLine(StringValueContainingTrueOrFalse)
        End If

        Console.ReadLine()
    End Sub
End Module

Results:

enter image description here

So, to answer your question about what’s going on, there’s a backstage conversion.

enter image description here

+1
source

Source: https://habr.com/ru/post/1584502/


All Articles