virtualmind virtualmind - 6 months ago 14
Vb.net Question

vb.net function to return an operator

i want the code to return an operator such as (+) or (-)
and then use that to perform a calculation. is that possible in vb.net?

PseudoCode

public function rOperator(params) as operator

if (..)
return +

else
return -
end if

end function


PseudoCode

Msgbox(1 rOperator 2)

Answer

As already said before, that is not possible. What you can do is create a dictionary of Func(Of T) and then invoke those by passing in your operator:

Sub Main
    Dim operations As New Dictionary(Of String, Func(Of Double, Double, Double))()

    'Set up operations for addition, subtractions, multipication, and division
    operations.Add("+", Function(l, r) l + r)
    operations.Add("-", Function(l, r) l - r)
    operations.Add("*", Function(l, r) l * r)
    operations.Add("/", Function(l, r) l / r)

    Dim result As Double = operations("+")(5, 5)
    Dim result2 As Double = operations("*")(5, 5)

    Console.WriteLine(result)
    Console.WriteLine(result2)

End Sub