virtualmind
virtualmind

Reputation: 60

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)

Upvotes: 0

Views: 54

Answers (1)

Chris Dunaway
Chris Dunaway

Reputation: 11216

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

Upvotes: 2

Related Questions