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.

2
  • 1
    wait.... 1-1=1? anyway, I think you should clarify what you want to do with this; it might be that a Func<int,int,int> suffices; i.e. Func<int,int,int> op = (x,y)=>x+y; var sum = op(2,3); // 5 (obviously this is C#, but can be translated to VB) Commented Aug 25, 2011 at 8:50
  • possible duplicate of Doing math in vb.net like Eval in javascript Commented Aug 25, 2011 at 8:57

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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;

2 Comments

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?
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.