0

I am writing a very simple math game. What I would like to be able to do is this:

Dim symbol as String

Private Sub Math()
    symbol = "+"
    1 symbol 1 = 2

    symbol = "-"
    1 symbol 1 = 0
end sub

I know this won't work, but it is the idea I want, thanks in advance.

Kuzon
  • 782
  • 5
  • 20
  • 49
  • 1
    wait.... 1-1=1? anyway, I think you should clarify what you want to do *with* this; it might be that a `Func` suffices; i.e. `Func op = (x,y)=>x+y; var sum = op(2,3); // 5` (obviously this is C#, but can be translated to VB) – Marc Gravell Aug 25 '11 at 08:50
  • possible duplicate of [Doing math in vb.net like Eval in javascript](http://stackoverflow.com/questions/1452282/doing-math-in-vb-net-like-eval-in-javascript) – Shadow The GPT Wizard Aug 25 '11 at 08:57

2 Answers2

1

Go with if else or switch case, use actual symbols inside the condition, something like

if symbol == "+":
return a+b;

if symbol == "-":
return a-b;
Adithya Surampudi
  • 4,354
  • 1
  • 17
  • 17
  • Yes, thankyou. I understand this way. But I have to do it in at little as possible amount of code. Is there a shorter way to do it? – Kuzon Aug 25 '11 at 08:52
  • There is no generic way to map a mathematical symbol string to what it depicts. To make it shorter for your case, you can use ternary operator like Dim result as Integer = If(symbol="+", a+b, a-b) – Adithya Surampudi Aug 25 '11 at 08:57
1

As Marc Gravell already mentioned, you could use a lambda expression. This is how it works in VB:

Private Sub Calculate(f As Func(Of Double, Double, Double))
    Dim a As Double = 1.5, b As Double = 3.14
    Console.WriteLine(f(a,b));
End Sub

Then you would call Calculate like this:

Calculate(Function(x,y) x+y)
Calculate(Function(x,y) x-y)
Calculate(Function(x,y) x*y)
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188