tags:

views:

42

answers:

1

Hi,

the idea is simple

The is a calculate function for example

Function Calculate (Byval v1 as integer, Byval v2 as integer, byval op as ????????) as double
return v1 op v2

End Function

Anybody tried this?

I don't want to use functions for every operation (multiply,divide, etc.).

I wanna pass a operator same as I pass the values. How come nobody ever had this need in VB?! Using enums could work but still... that's not it...

+3  A: 

You can't pass an operator, but you can pass a Function that implements the operator. Here's a short but complete program to demonstrate:

Public Shared Function Add(a As Integer, b As Integer) As Integer
    Return a + b
End Function

Public Shared Function Divide(a As Integer, b As Integer) As Integer
    Return a \ b ''# Backwards \ is VB integer division
End Function

Public Shared Function Calculate(a As Integer, b As Integer, op As Func(Of Integer, Integer, Integer))
    Return op(a, b)
End Function

Public Shared Sub Main()
    Console.Write("Divide:  ")
    Console.WriteLine(Calculate(4,2, AddressOf Divide))
    Console.Write("Add:  ")
    Console.WriteLine(Calculate(4,2, AddressOf Add))
    Console.Write("Multiply:  ")
    Console.WriteLine(Calculate(4,2, Function(x,y) x * y))
    Console.Write("Subtract:  ")
    Console.WriteLine(Calculate(4,2, Function(x,y)
                                          Return x - y
                                     End Function))
    Console.ReadKey(True)
End Sub

Note that I typed this directly into the reply window, so there's likely a mistake in there somewhere. Also note that the last example only works in Visual Studio 2010. But the gist of the answer is accurate.

Joel Coehoorn
I didn't think of it like this!
Besnik
Let me formulate the question better.
Besnik