Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass function as a parameter in vb.net?

I have class that performs many similar yet different read/write operations to an excel file. All of these operations are defined in separate functions. They all have to be contained within the same long block of code (code that checks and opens a file, saves, closes, etc). What is reasonable way to not have to duplicate this code each time? The problem is that I can't just one method containing all of the shared code before I execute the code that is different for each method because that code must be contained within many layers of if, try, and for statements of the shared code.

Is it possible to pass a function as a parameter, and then just run that function inside the shared code? Or is there a better way to handle this?

like image 256
Bernoulli Lizard Avatar asked Oct 21 '13 15:10

Bernoulli Lizard


2 Answers

Focusing on the actual question:

Is it possible to pass a function as a parameter

Yes. Use AddressOf TheMethod to pass the method into another method. The argument type must be a delegate whose signature matches that of the target method. Inside the method, you treat the parameter as if it were the actual method. Example:

Sub Foo()
    Console.WriteLine("Foo!")
End Sub

Sub Bar()
    Console.WriteLine("Bar!")
End Sub

Sub CallSomething(f As Action)
    f()
End Sub

' … somewhere:
CallSomething(AddressOf Foo)
CallSomething(AddressOf Bar)

As I said, the actual parameter type depends on the signature of the method you’d like to pass. Use either Action(Of T) or Func(Of T) or a custom delegate type.

However, in many cases it’s actually appropriate to use an interface instead of a delegate, have different classes implement your interface, and pass objects of those different classes into your method.

like image 98
Konrad Rudolph Avatar answered Sep 18 '22 12:09

Konrad Rudolph


Declare your parameter as Func(Of T) or Action(Of T).

Which one you should use depend on your methods signature. I could give you more precise answer if you gave us one.

like image 30
MarcinJuraszek Avatar answered Sep 22 '22 12:09

MarcinJuraszek