Convert String to Boolean, it generates me error

0
    Dim condicion As String
    Dim cond As Boolean
    Dim a As Integer
    Dim b As Integer
    a = 25
    b = 0
    condicion = "a >= 20 And b <= 50"
    cond = Convert.ToBoolean(condicion)
    If cond Then
        b = a
    End If
    Console.Out.WriteLine(a)
    Console.Out.WriteLine(b)

    Console.ReadLine()
End Sub

I have the following question, I have a variable String:

Dim condicion As String = "a >= 20 And b <= 50"

I would like to convert it to boolean to be able to use it in an if and I can not find a way to do it, it would be very helpful, thanks, and I'll test with Convert.ToBoolean (condition) and I still get an error, thanks

    
asked by bryan 27.02.2018 в 22:03
source

2 answers

1

You can not.

Convert.ToXXX what it does is transform a type of variable into another type of variable.

What you are trying to do is interpret a code in execution time, and VB (or c #) is prepared for that.

Javascript if you do so, with the Eval instruction.

for more references see the Convert.ToBoolean page

    
answered by 27.02.2018 / 22:43
source
3

Although the answer of @gbianchi is correct, I am going to give in mine an alternative that is perhaps little known and that for simple things it can serve.

This is about using DataTable.Compute , which evaluates a condition passed as string.

This is combined with string interpolation (use in this case the one provided by C # from version 6, and VB.net from 14, in the previous ones we should use String.Format ).

That would be your code:

Dim condicion As String
Dim cond As Boolean
Dim a As Integer
Dim b As Integer
a = 25
b = 0
condicion As String = $"{a} >= 20 and {b} <= 50"
Dim dt As DataTable = New DataTable()
cond = dt.Compute(condicion, Nothing)
If cond Then
    b = a
End If
Console.Out.WriteLine(a)
Console.Out.WriteLine(b)

Console.ReadLine()
    
answered by 28.02.2018 в 09:18